/// <summary> /// 将json字符串反序列化成对象,json中须包含__type信息 /// </summary> /// <param name="input"></param> /// <returns></returns> public static object DeserializeObject(string input) { JavaScriptSerializer serializer = new JavaScriptSerializer(new SimpleTypeResolver()); serializer.MaxJsonLength = JSONSerializerFactory.GetMaxJsonLength(); JSONSerializerFactory.RegisterConverters(serializer); return(serializer.DeserializeObject(input)); }
public static T DeserializeString <T>(string input) { Type type = typeof(T); JavaScriptSerializer serializer = JSONSerializerFactory.GetJavaScriptSerializer(type); serializer.RegisterConverters(InternalDateTimeConverter.Instances); return((T)serializer.Deserialize(input, type)); }
/// <summary> /// 将字符串反序列化为对象。这里的日期类型会经过内部的转换器,此方法不建议在js端使用 /// </summary> /// <param name="input"></param> /// <param name="type"></param> /// <returns></returns> public static object DeserializeString(string input, Type type) { type.NullCheck("type"); JavaScriptSerializer serializer = JSONSerializerFactory.GetJavaScriptSerializer(type); serializer.RegisterConverters(InternalDateTimeConverter.Instances); return(serializer.Deserialize(input, type)); }
/// <summary> /// 序列化对象 /// </summary> /// <param name="input">要序列化的对象</param> /// <param name="type">要序列化的类型,可以是input的基类或input实现的接口</param> /// <param name="resolverTypeLevel">要输出类型信息的级别深度</param> /// <returns>序列化结果</returns> /// <remarks>替代系统提供的序列化调用</remarks> public static string Serialize(object input, Type type, int resolverTypeLevel) { JavaScriptSerializer serializer = resolverTypeLevel > 0 ? JSONSerializerFactory.GetJavaScriptSerializer(input.GetType()) : JSONSerializerFactory.GetJavaScriptSerializer(); serializer.MaxJsonLength = JSONSerializerFactory.GetMaxJsonLength(); input = PreSerializeObject(input, type, resolverTypeLevel - 1); return(serializer.Serialize(input)); }
/// <summary> /// 序列化,结果中包含__type信息 /// </summary> /// <param name="input"></param> /// <param name="addPrimitiveConverters">是否增加原始类型的转换器</param> /// <returns></returns> public static string SerializeWithType(object input, bool addPrimitiveConverters = false) { JavaScriptSerializer serializer = new JavaScriptSerializer(new SimpleTypeResolver()); serializer.MaxJsonLength = JSONSerializerFactory.GetMaxJsonLength(); JSONSerializerFactory.RegisterConverters(serializer); if (addPrimitiveConverters) { serializer.RegisterConverters(InternalDateTimeConverter.Instances); } return(serializer.Serialize(input)); }
/// <summary> /// 预处理序列化对象,通过调用此函数,可对序列化进行预处理 /// </summary> /// <param name="input">要序列化的对象</param> /// <param name="targetType">要序列化的类型,可以是input的基类或input实现的接口</param> /// <param name="resolverTypeLevel">要输出类型信息的级别深度</param> /// <returns>处理结果</returns> /// <remarks>预处理序列化对象,通过调用此函数,可对序列化进行预处理</remarks> public static object PreSerializeObject(object input, Type targetType, int resolverTypeLevel) { object result = input; if (input != null) { JavaScriptConverter converter = JSONSerializerFactory.GetJavaScriptConverter(input.GetType()); if (converter != null) { result = converter.Serialize(input, JSONSerializerFactory.GetJavaScriptSerializer()); } else { if ((input is ValueType) == false && (input is string) == false && (input is IDictionary) == false) { if (input is IEnumerable) { result = SerializeEnumerableData((IEnumerable)input, targetType, resolverTypeLevel); } else { result = SerializeReferenceData(input, targetType, resolverTypeLevel); } } } } if (resolverTypeLevel > 0 && result is IDictionary <string, object> ) { Dictionary <string, object> resultDict = result as Dictionary <string, object>; if (resultDict.ContainsKey("__type") == false) { resultDict["__type"] = input.GetType().AssemblyQualifiedName; } } return(result); }
/// <summary> /// 将对象input转换成类别为type的对象,如果不能直接转换则调用JSON转换 /// </summary> /// <param name="input">要转换的对象</param> /// <param name="type">要转换成的类型</param> /// <param name="level">调用级别</param> /// <returns>转换结果</returns> private static object DeserializeObject(object input, Type type, int level) { if (level > 3) { //重点考虑目标类型也是Dictionary<string, object>的情况 if (type != typeof(Dictionary <string, object>)) { throw new ApplicationException(string.Format(Resources.DeluxeJsonResource.E_InvokeLevelTooDeep, level)); } else { return(input); } } object result = null; if (input != null) //Added by shenzheng 2008-3-10 { if (type.IsEnum) { result = DataConverter.ChangeType(input, type); } else { if (type.IsAssignableFrom(input.GetType()) && type != typeof(Dictionary <string, object>)) { result = input; } else if (type.IsPrimitive && typeof(IConvertible).IsAssignableFrom(type)) { //if (type.GetInterface(typeof(IConvertible).AssemblyQualifiedName) != null) result = Convert.ChangeType(input, type, CultureInfo.InvariantCulture); } else { if (input is object[]) { object tempResult = DeserializeArrayObject((object[])input, type, level); if (tempResult == null) { throw new ApplicationException(string.Format(Resources.DeluxeJsonResource.E_CanNotConvertTypeTo, input.GetType().AssemblyQualifiedName, type.AssemblyQualifiedName)); } else { result = tempResult; } } else if (type.IsEnum) { result = DataConverter.ChangeType(input.GetType(), input, type); } else { Dictionary <string, object> dictionary = input as Dictionary <string, object>; if (type != null && dictionary != null && dictionary.ContainsKey("__type") == false) { dictionary["__type"] = type.AssemblyQualifiedName; } JavaScriptSerializer serializer = JSONSerializerFactory.GetJavaScriptSerializer(type); if (dictionary != null) { serializer.RegisterConverters(InternalDateTimeConverter.Instances); } string str = string.Empty; if (input is string) { str = (string)input; } else { str = serializer.Serialize(input); } result = serializer.DeserializeObject(str); } result = DeserializeObject(result, type, ++level); } } } return(result); }
public static void DescribeComponent(object instance, ScriptComponentDescriptor descriptor, IUrlResolutionService urlResolver, IControlResolver controlResolver) { // validate preconditions if (instance == null) { throw new ArgumentNullException("instance"); } if (descriptor == null) { throw new ArgumentNullException("descriptor"); } if (urlResolver == null) { urlResolver = instance as IUrlResolutionService; } if (controlResolver == null) { controlResolver = instance as IControlResolver; } // describe properties // PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(instance); PropertyInfo[] properties = instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (PropertyInfo prop in properties) { ScriptControlPropertyAttribute propAttr = null; ScriptControlEventAttribute eventAttr = null; string propertyName = prop.Name; System.ComponentModel.AttributeCollection attribs = new System.ComponentModel.AttributeCollection(Attribute.GetCustomAttributes(prop, false)); // Try getting a property attribute propAttr = (ScriptControlPropertyAttribute)attribs[typeof(ScriptControlPropertyAttribute)]; if (propAttr == null || !propAttr.IsScriptProperty) { // Try getting an event attribute eventAttr = (ScriptControlEventAttribute)attribs[typeof(ScriptControlEventAttribute)]; if (eventAttr == null || !eventAttr.IsScriptEvent) { continue; } } // attempt to rename the property/event ClientPropertyNameAttribute nameAttr = (ClientPropertyNameAttribute)attribs[typeof(ClientPropertyNameAttribute)]; if (nameAttr != null && !string.IsNullOrEmpty(nameAttr.PropertyName)) { propertyName = nameAttr.PropertyName; } // determine whether to serialize the value of a property. readOnly properties should always be serialized //bool serialize = true;// prop.ShouldSerializeValue(instance) || prop.IsReadOnly; //if (serialize) //{ // get the value of the property, skip if it is null Control c = null; object value = prop.GetValue(instance, new object[0] { }); if (value == null) { continue; } // convert and resolve the value if (eventAttr != null && prop.PropertyType != typeof(String)) { throw new InvalidOperationException("ScriptControlEventAttribute can only be applied to a property with a PropertyType of System.String."); } else { if (!prop.PropertyType.IsPrimitive && !prop.PropertyType.IsEnum) { if (prop.PropertyType == typeof(Color)) { value = ColorTranslator.ToHtml((Color)value); } else { // TODO: Determine if we should let ASP.NET AJAX handle this type of conversion, as it supports JSON serialization //TypeConverter conv = prop.Converter; //value = conv.ConvertToString(null, CultureInfo.InvariantCulture, value); //if (prop.PropertyType == typeof(CssStyleCollection)) // value = (new CssStyleCollectionJSCoverter()).Serialize(value, new JavaScriptSerializer()); //if (prop.PropertyType == typeof(Style)) // value = (new CssStyleCollectionJSCoverter()).Serialize(((Style)value).GetStyleAttributes(null), new JavaScriptSerializer()); Type valueType = value.GetType(); JavaScriptConverterAttribute attr = (JavaScriptConverterAttribute)attribs[typeof(JavaScriptConverterAttribute)]; JavaScriptConverter converter = attr != null ? (JavaScriptConverter)TypeCreator.CreateInstance(attr.ConverterType) : JSONSerializerFactory.GetJavaScriptConverter(valueType); if (converter != null) { value = converter.Serialize(value, JSONSerializerFactory.GetJavaScriptSerializer()); } else { value = JSONSerializerExecute.PreSerializeObject(value); } //Dictionary<string, object> dict = value as Dictionary<string, object>; //if (dict != null && !dict.ContainsKey("__type")) // dict["__type"] = valueType.AssemblyQualifiedName; } } if (attribs[typeof(IDReferencePropertyAttribute)] != null && controlResolver != null) { c = controlResolver.ResolveControl((string)value); } if (attribs[typeof(UrlPropertyAttribute)] != null && urlResolver != null) { value = urlResolver.ResolveClientUrl((string)value); } } // add the value as an appropriate description if (eventAttr != null) { if (!string.IsNullOrEmpty((string)value)) { descriptor.AddEvent(propertyName, (string)value); } } else if (attribs[typeof(ElementReferenceAttribute)] != null) { if (c == null && controlResolver != null) { c = controlResolver.ResolveControl((string)value); } if (c != null) { value = c.ClientID; } descriptor.AddElementProperty(propertyName, (string)value); } else if (attribs[typeof(ComponentReferenceAttribute)] != null) { if (c == null && controlResolver != null) { c = controlResolver.ResolveControl((string)value); } if (c != null) { //ExtenderControlBase ex = c as ExtenderControlBase; //if (ex != null && ex.BehaviorID.Length > 0) // value = ex.BehaviorID; //else value = c.ClientID; } descriptor.AddComponentProperty(propertyName, (string)value); } else { if (c != null) { value = c.ClientID; } descriptor.AddProperty(propertyName, value); } } //} // determine if we should describe methods foreach (MethodInfo method in instance.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public)) { ScriptControlMethodAttribute methAttr = (ScriptControlMethodAttribute)Attribute.GetCustomAttribute(method, typeof(ScriptControlMethodAttribute)); if (methAttr == null || !methAttr.IsScriptMethod) { continue; } // We only need to support emitting the callback target and registering the WebForms.js script if there is at least one valid method Control control = instance as Control; if (control != null) { // Force WebForms.js control.Page.ClientScript.GetCallbackEventReference(control, null, null, null); // Add the callback target descriptor.AddProperty("_callbackTarget", control.UniqueID); } break; } }