序列化 (Serialization)将对象的状态信息转换为可以存储或传输的形式(如json,xml)的过程。
1.简单JSON:
"{'BookID':'123','PublishDate':'2011-1-2','Price':23.5}"
public class Book { public string BookID { get; set; } public DateTime PublishDate { get; set; } public decimal Price { get; set; } }
2.一级嵌套的json:
{"name":"lex","age":26,"addr":{"city":"NanTong","province":"JiangSu"}}
public class UserInfo { public string name { get; set; } public int age { get; set; } public address addr { get; set; } } public class address { public string city { get; set; } public string province { get; set; } }
3.不确定类型的json使用JObject:
static void Main(string[] args) { string str = "{title:123,body:456,list:{title:'标题',body:'内容'}}"; JObject o = JObject.Parse(str); Console.WriteLine(o["title"]); Console.WriteLine(o["body"]); Console.WriteLine(o["list"]["title"]); Console.WriteLine(o["list"]["body"]); Console.ReadKey(); }
4.多级嵌套的json:
//bootstrap treeview,数据结构为 [ { id:'1',//节点id text: '父节点',//节点显示文本 icon: 'glyphicon glyphicon-cloud-download',//节点图标样式 nodes:[{id:'2',text:'子节点'}] //子节点 } ] //zTree [ { "id" : "1","name" : "父节点1","children" : [{id:'4',name:'子节点1'}] },{ "id" : "2","name" : "父节点2","children" : [{id:'5',name:'子节点2'}] },{ "id" : "3","name" : "父节点3","children" : [{id:'6',name:'子节点3'}] } ]
/// <summary> /// 树形实体 /// </summary> public class Tree { /// <summary> /// 当前ID /// </summary> public string id { get; set; } /// <summary> /// 文本 /// </summary> public string text { get; set; } /// <summary> /// 附加信息 /// </summary> public string Tag { get; set; } /// <summary> /// 节点图标 /// </summary> public string Icon { get; set; } /// <summary> /// 子级 /// </summary> public List<Tree> nodes { get; set; } }不同字段名称,相同层级结构,使用了动态改变属性序列化名称方案后,前后台完全解绑了,不管前台使用什么树形控件,后台实体只有一个树形实体。我们要做的仅仅是设置一下字段映射关系而已。
/// <summary> /// 动态属性转换约定 /// </summary> /// <remarks> /// 处理场景 树形结构数据 后台代码实体定义 为 Id Childrens 但是前台树形控件所需数据结构为 id,nodes /// 这个时候可以使用该属性约定转换类 动态设置 序列化后字段名称 /// </remarks> /// <example> /// JsonSerializerSettings setting = new JsonSerializerSettings(); /// setting.ContractResolver = new PropsContractResolver(new Dictionary<string,string> { { "Id","id" },{ "Text","text" },{ "Childrens","nodes" } }); /// string AA = JsonConvert.SerializeObject(cc,Formatting.Indented,setting); /// </example> public class PropsContractResolver : DefaultContractResolver { Dictionary<string,string> dict_props = null; /// <summary> /// 构造函数 /// </summary> /// <param name="props">传入的属性数组</param> public PropsContractResolver(Dictionary<string,string> dictPropertyName) { //指定字段要序列化成什么名称 this.dict_props = dictPropertyName; } protected override string ResolvePropertyName(string propertyName) { string newPropertyName = string.Empty; if (dict_props != null && dict_props.TryGetValue(propertyName,out newPropertyName)) { return newPropertyName; } else { return base.ResolvePropertyName(propertyName); } } }
/// <summary> /// 树形实体 /// </summary> public class Tree { /// <summary> /// 当前ID /// </summary> public string Id { get; set; } /// <summary> /// 文本 /// </summary> public string Text { get; set; } /// <summary> /// 附加信息 /// </summary> public string Tag { get; set; } /// <summary> /// 节点图标 /// </summary> public string Icon { get; set; } /// <summary> /// 子级 /// </summary> public List<Tree> Childrens { get; set; } } string type="zTree"; //字段映射关系 Dictionary<string,string> _dictProp = null; if(type=="zTree") { _dictProp = new Dictionary<string,string> { { "Icon","icon" },"name" },"children" } }; } else if(type=="treeview") { _dictProp = new Dictionary<string,"nodes" } }; } // 序列化设置 JsonSerializerSettings PropSettings = new JsonSerializerSettings { ContractResolver = new PropsContractResolver(_dictProp) }; return JsonConvert.SerializeObject(new List<Tree>(),Formatting.None,PropSettings);5.Json数组
"[{'a':'aaa','b':'bbb','c':'ccc'},{'a':'aaa2','b':'bbb2','c':'ccc2'}]"
public class Customer { public string a { get; set; } public string b { get; set; } public string c { get; set; } public string Other { get; set; } public Customer() { a = ""; b = ""; c = ""; Other = null; } }
string jsonText = "[{'a':'aaa','c':'ccc2'}]"; //方法1 JArray ja =(JArray) JsonConvert.DeserializeObject(jsonText); JObject o = (JObject)ja[1]; Console.WriteLine(o["a"]); Console.WriteLine(ja[1]["a"]); //方法2 List<Customer> _list = JsonConvert.DeserializeObject<List<Customer>>(jsonText); Console.WriteLine(_list[1].a); foreach (Customer c in _list) { Console.WriteLine(c.c); }原文链接:https://www.f2er.com/json/289281.html