C# Json反序列化
Json反序列化有两种方式【本人】,一种是生成实体的,方便处理大量数据,复杂度稍高,一种是用匿名类写,方便读取数据,较为简单。
使用了Newtonsoft.Json,可以自行在nuget中导入
Json源数据:
var data = "{'jingdong_ldop_receive_trace_get_responce':{'code':'0','querytrace_result':{'data':[{'opeTitle':'快递签收','opeRemark':'货物已交付京东物流','opeTime':'2011/04/17 18:23:20','opeName':'京东快递','waybillCode':'bc00000001'},{'opeTitle':'站点验货','opeRemark':'货物已分配,等待配送','opeTime':'2011/04/23 08:29:56','opeName':'京东快递','waybillCode':'bc00000001'},{'opeTitle':'配送员收货','opeRemark':'配送员开始配送,请您准备收货,','opeTime':'2011/04/23 08:36:28','opeName':'京东快递','waybillCode':'bc00000001'},{'opeTitle':'妥投','opeRemark':'货物已完成配送,感谢您选择京东物流','opeTime':'2011/04/23 09:47:13','opeName':'京东快递','waybillCode':'bc00000001'}],'messsage':'成功','code':100}}}";
第一种:是用匿名方法生成,按照Json的格式,从外到内,一步一步写,非数组用new{},数组用new[]{},名字必须与json中名字一致
//使用匿名变量构造 { var JsonDataForVar = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(data, new { jingdong_ldop_receive_trace_get_responce = new { code = string.Empty, querytrace_result = new { data = new[] { new { opeTitle=string.Empty, opeRemark=string.Empty, opeTime=string.Empty, waybillCode=string.Empty, opeName=string.Empty } } } } }); foreach (var item in JsonDataForVar.jingdong_ldop_receive_trace_get_responce.querytrace_result.data) { var a = item.opeTitle; var b = item.opeRemark; var c = item.opeTime; var d = item.waybillCode; var f = item.opeName; } }
第二种:使用实体
//实体部分,建议从内到外写实体,名字必须与json中名字一致【简便方法,搜索Json转实体,将Json字符串导入,自动生成实体】
public class Item { public string opeTitle { get; set; } public string opeRemark { get; set; } public string opeTime{ get; set; } public string waybillCode { get; set; } public string opeName { get; set; } } public class JdResult { public string code { get; set; } public string msg { get; set; } public List<Item> data { get; set; } } public class JdResponce { public string code { get; set; } public JdResult querytrace_result { get; set; } } public class JdBody { public JdResponce jingdong_ldop_receive_trace_get_responce { get; set; } }
//方法
//使用实体构造 { var JsonDataForClass = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(data, new JdBody()); foreach (var item in JsonDataForClass.jingdong_ldop_receive_trace_get_responce.querytrace_result.data) { var a = item.opeTitle; var b = item.opeRemark; var c = item.opeTime; var d = item.waybillCode; var f = item.opeName; } }