/// <summary> /// 转指定类型的KeyValuePair<,>为JObject /// </summary> private static JObject ConvertKeyValuePairGenericToObject(object obj) { JObject res = new JObject(); Type keyType = obj.GetType().GetGenericArguments()[0]; Type valueType = obj.GetType().GetGenericArguments()[1]; object key = null, value = null; if (JUtil.GetProperty(obj.GetType(), "Key", obj, ref key)) { if (JUtil.GetProperty(obj.GetType(), "Value", obj, ref value)) { if (JUtil.IsValueType(keyType)) { res.Add(key.ToString(), ConvertToJValue(value)); } else { res.Add("Key", ConvertToJValue(key)); res.Add("Value", ConvertToJValue(value)); } } } return(res); }
/// <summary> /// 转 IDictionary<,>为JObject /// </summary> private static JObject ConvertDictionaryGenericToObject(object obj) { JObject res = new JObject(); IEnumerable tempEnumerable = obj as IEnumerable; IEnumerator tempEnumerator = tempEnumerable.GetEnumerator(); while (tempEnumerator.MoveNext()) { object tempKV = tempEnumerator.Current; object key = null; if (JUtil.GetProperty(tempKV.GetType(), "Key", tempKV, ref key)) { if (null != key) { object value = null; if (JUtil.GetProperty(tempKV.GetType(), "Value", tempKV, ref value)) { res.Add(key.ToString(), ConvertToJValue(value)); } } } } return(res); }
/// <summary> /// 序列化对象 /// </summary> public object ToDeserialize(Type type) { if (!JUtil.CanInstance(type)) { return(null); } if (type.IsArray) { object defaultValue = JUtil.CreateInstance(type, mValues.Count); Type eleType = type.GetElementType(); for (int i = 0; i < mValues.Count; ++i) { type.GetMethod("SetValue", new Type[] { typeof(object), typeof(int) }).Invoke(defaultValue, new object[] { mValues[i].ToDeserialize(eleType), i }); } return(defaultValue); } else { object defaultValue = JUtil.CreateInstance(type); if (JUtil.IsListGenericType(type)) { if (JUtil.IsListGenericType(type)) { Type t = type.GetGenericArguments()[0]; for (int i = 0; i < mValues.Count; ++i) { type.GetMethod("Insert", new Type[] { typeof(int), t }).Invoke(defaultValue, new object[] { i, mValues[i].ToDeserialize(t) }); } return(defaultValue); } } if (JUtil.IsDictionaryGenericType(type)) { Type keyType = type.GetGenericArguments()[0]; Type valueType = type.GetGenericArguments()[1]; Type keyValueType = typeof(KeyValuePair <,>).MakeGenericType(new Type[] { keyType, valueType }); for (int i = 0; i < mValues.Count; ++i) { object keyVlaue = mValues[i].ToDeserialize(keyValueType); object key = null, value = null; if (JUtil.GetProperty(keyValueType, "Key", keyVlaue, ref key)) { JUtil.GetProperty(keyValueType, "Value", keyVlaue, ref value); } if (null != key) { type.GetMethod("Add", new Type[] { keyType, valueType }).Invoke(defaultValue, new object[] { key, value }); } } } return(defaultValue); } }