码迷,mamicode.com
首页 > Web开发 > 详细

不同Json格式的反序列化处理

时间:2015-07-30 10:52:35      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

最近换工作 从客户端转到Web端 第一个任务就是去页面上抓取数据 用到的是JSON 因为json的格式有点怪 所以 就在JSON反序列化上面 花了一点时间

首先用到的工具是http://www.newtonsoft.com/json

然后 根据JSON创建对应的对象类

下面分三种JSON形式

Demo1:

json:{"id":"1","name":"aaa1","work":"aaa2"}

这个是最常见的json格式

对象类:

技术分享
1 public class worker
2 {
3   public string id { get; set; }
4 
5   public string name { get; set; }
6 
7   public string work { get; set; }
8 }
View Code

输出:

技术分享
1 string jsonStr="....";   //json
2 var x = JsonConvert.DeserializeObject<worker>(jsonStr);
3 return x.name+"|"+x.work;
View Code

Demo2:

json:[{"id":"1","name":"aaa1","work":"aaa2"},{"id":"2","name":"bbb1","work":"bbb2"},{"id":"3","name":"ccc1","work":"ccc2"}]

这个是带数组的json格式

对象类:

技术分享
1 public class worker
2 {
3         public string id { get; set; }
4         public string name { get; set; }
5         public string work { get; set; }
6 }
View Code

输出:

技术分享
1 string jsonStr="...":
2 List<worker> lst = JsonConvert.DeserializeObject<List<worker>>(jsonStr);
3 
4 for(int i=0;i<jsonStr.Count;i++)
5 {
6       if(lst[i].id=="1")
7            return lst[i].name;      
8 }    
View Code

Demo3:

json:[{"Department":{"Leader":"x1","number":"10"},"worker":[{"id":"1","name":"aaa1","work":"aaa2"},{"id":"2","name":"bbb1","work":"bbb2"},{"id":"3","name":"ccc1","work":"ccc2"}]},{"Department":{"Leader":"x2","number":"20"},"worker":[{"id":"4","name":"ddd1","work":"ddd2"},{"id":"5","name":"eee1","work":"eee2"},{"id":"6","name":"fff1","work":"fff2"}]}]

这是个多层嵌套并且带数组的json格式

对象类:

public class Company
{
    public string Department { get; set; }
    public worker[] WorkerInfo{ get; set; }   //这里注意这个worker类是个数组
}

public class worker
{
    public string id {get; set;}
    public string name {get; set;}
    public string work {get; set;}
}        

输出:

技术分享
Company[] c = JsonConvert.DeserializeObject<Company[]>(jsonStr);

foreach(Compant c1 in c)
{
    Department d =c1.Department;
    WorkerInfo[] wi=c1.WorkerInfo;  

    string leader=d.leader;
    
    foreach(WorkerInfo wi1 in wi)
    {
          string name=wi1.name;
          return name+leader;
    }  
}
View Code

 

不同Json格式的反序列化处理

标签:

原文地址:http://www.cnblogs.com/CoffeeEddy/p/4688411.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!