《JSON序列化》一
2016-04-06 10:44
691 查看
JSON格式在描述一个JavaScript对象一般都能胜任的,包括字符串、数字、Bool、数组都能在格式中分辨清楚。
JSON序列化图解
1.Object对象
2.1数组对象
微软自身就有不只一种JSON的序列化机制,例如WCF下的JSON序列化。还有诸如Json.net之类的第三方工具.
另外,JSON序列化还要关心其可扩展性。毕竟复杂对象的序列化,尤其是带有相互引用关系的对象,很容易产生无限递归,导致堆栈溢出。微软的Asp.netAJAX就提供了一种定制序列化的手段,编写一个Converter:
JSONSerializerExecute.RegisterConverter(typeof(DemoEntityConverter));
在一个AppDomain中,仅仅注册一次就行。上面的总结,只是我们自己扩展了一个类,这个类可以解决我们在序列化过程中产生的对象之间循环引用问题,这个问题很容易产生无限递归,导致堆栈溢出。至于客户端怎么调用,我们来看下一篇博客。
JSON序列化图解
1.Object对象
2.1数组对象
微软自身就有不只一种JSON的序列化机制,例如WCF下的JSON序列化。还有诸如Json.net之类的第三方工具.
另外,JSON序列化还要关心其可扩展性。毕竟复杂对象的序列化,尤其是带有相互引用关系的对象,很容易产生无限递归,导致堆栈溢出。微软的Asp.netAJAX就提供了一种定制序列化的手段,编写一个Converter:
public class DemoEntityConverter : JavaScriptConverter { public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { DemoEntity entity = new DemoEntity(); entity.P1 = DictionaryHelper.GetValue(dictionary, "P1", string.Empty); entity.P2 = DictionaryHelper.GetValue(dictionary, "P2", string.Empty); entity.P3 = DictionaryHelper.GetValue(dictionary, "P3", string.Empty); //解决对象之间循环引用的问题 if (dictionary.ContainsKey("Entity2")) { entity.Entity2 = JSONSerializerExecute.Deserialize<DemoEntity2>(dictionary["Entity2"]); entity.Entity2.Entity = entity; } return entity; } public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { IDictionary<string, object> dictionary = new Dictionary<string, object>(); DemoEntity entity = (DemoEntity)obj; //仅序列化需要的属性,减少json串大小 DictionaryHelper.AddNonDefaultValue<string, object>(dictionary, "P1", entity.P1); DictionaryHelper.AddNonDefaultValue<string, object>(dictionary, "P2", entity.P2); DictionaryHelper.AddNonDefaultValue<string, object>(dictionary, "P3", entity.P3); dictionary.Add("Entity2", entity.Entity2); return dictionary; } public override IEnumerable<Type> SupportedTypes { get { return new Type[] { typeof(DemoEntity) }; } } }上面的代码中,就为类型DemoEntity,定制了一个JSON序列化器。当然在使用之前,需要先为类型DemoEntity,注册此序列化器。
JSONSerializerExecute.RegisterConverter(typeof(DemoEntityConverter));
在一个AppDomain中,仅仅注册一次就行。上面的总结,只是我们自己扩展了一个类,这个类可以解决我们在序列化过程中产生的对象之间循环引用问题,这个问题很容易产生无限递归,导致堆栈溢出。至于客户端怎么调用,我们来看下一篇博客。
相关文章推荐
- JS密码生成与强度检测完整实例(附demo源码下载)
- js--语法--for和for-in;访问对象的属性.和[]的区别
- JS隐藏gridview最后一列
- JSOI2015
- <json基础教程>
- JS控制伪元素的方法汇总
- DataTable 对象 转换为Json 字符串
- JS中六种数据类型(一)——undefined
- 全屏滚动插件pagePiling.js
- 自适应滑动插件swiper.js
- FullPage.js参数和函数详解
- 页面加载进度条pace.js
- 轻松实现全屏滚动-FullPage.js
- 跨浏览器本地存储-Store.js
- JS中浮点数运算不精准
- JS实现把鼠标放到链接上出现滚动文字的方法
- js中的“十二行诗” ----12行JS代码的DoS攻击分析及其防御
- 使用 AMD、CommonJS 及 ES Harmony 编写模块化的 JavaScript
- Content Editor Webpart(三)使用JSOM
- JS设置cookie、读取cookie、删除cookie