C#下JSON字符串的反序列化

C#下JSON字符串的反序列化,一般都是用newtonsoft.json,比较方便。.net当然也有提供相应功能,但觉得比较复杂。

所谓反序列化,就是将一个包含JSON内容的字符串,转换回指定对象(不一定是转换回JSON对象)。

方法是:

using Newtonsoft.Json;

。。。

JsonConvert.DeserializeObject<。。。>(strJson)

示例1:

[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public class ViewTag  
  2. {  
  3.     public int ViewId { getset; }  
  4.     public string Name { getset; }  
  5.     public bool IsValid { getset; }  
  6.     public int Seq { getset; }  
  7.     public byte ChangeType { getset; }  
  8. }  
  9.   
  10. string strJson = "[{'ViewId':14,'Name':'view 1','IsValid':true,'Seq':'1','ChangeType':0},{'ViewId':15,'Name':'view 2','IsValid':true,'Seq':'2','ChangeType':0}]";  
  11.   
  12. List<ViewTag> list = JsonConvert.DeserializeObject<List<ViewTag>>(strJson);  

上述例子中,json字符串内,每个json元素的数据结构都一样。但假如不一样,怎么办?

示例2:

[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. string strJson = @"[{  
  2.     'id':1,  
  3.     'text':'All Object',  
  4.     'iconCls':'',   
  5.     'children':[{  
  6.         'id':11,  
  7.         'text':'Key attributes',  
  8.         'children':[{  
  9.             'id':111,  
  10.             'text':'Item1'  
  11.         },{  
  12.             'id':112,  
  13.             'text':'Item2'  
  14.         },{  
  15.             'id':113,  
  16.             'text':'Item3'  
  17.         }]  
  18.     },{  
  19.         'id':12,  
  20.         'text':'Service table 1',  
  21.         'state':'closed',  
  22.         'children':[{  
  23.             'id':121,  
  24.             'text':'Service 1'  
  25.         },{  
  26.             'id':122,  
  27.             'text':'Service 2'  
  28.         },{  
  29.             'id':123,  
  30.             'text':'Service 3'  
  31.         }]  
  32.     },{  
  33.         'id':13,  
  34.         'text':'Service table 2',  
  35.         'state':'closed',  
  36.         'children':[{  
  37.             'id':131,  
  38.             'text':'Service 1'  
  39.         },{  
  40.             'id':132,  
  41.             'text':'Service 2'  
  42.         },{  
  43.             'id':133,  
  44.             'text':'Service 3'  
  45.         }]  
  46.     },{  
  47.         'id':14,  
  48.         'text':'Service table 3'  
  49.     }]  
  50. }]";  
  51.             return JsonConvert.DeserializeObject<List<object>>(strJson);  

不管三七二十一,将泛型对象定为 object 即可。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值