当前位置: 移动技术网 > IT编程>开发语言>c# > C#中Json反序列化的实现方法

C#中Json反序列化的实现方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

前言

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;
    }
   }

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网