首页 > 代码库 > 使用 dynamic 标记解析JSON字符串

使用 dynamic 标记解析JSON字符串

参考页面:

http://www.yuanjiaocheng.net/CSharp/csharprumenshili.html

http://www.yuanjiaocheng.net/CSharp/csharp-class.html

http://www.yuanjiaocheng.net/CSharp/csharp-variable.html

http://www.yuanjiaocheng.net/CSharp/Csharp-data-types.html

http://www.yuanjiaocheng.net/CSharp/cshart-value-reference-type.html

1 string jsonStr = "{\"data\": {\"ssoToken\": \"70abd3d8a6654ff189c482fc4842468c\",\"account\":\"admin\",\"userType\":\"platformAdmin\",\"realName\": \"超级管理员\",\"sex\": 0,\"sexName\":\"男\",\"email\":\"alina_dong@163.com\",\"mobile\":\"15120757948\",\"createdDt\": \"2013-08-16 00:00:00\",\"updatedDt\": \"2014-12-10 00:00:00\" },\"isSuccess\": true}"; 

当 .Net 程序接收到了这段JSON字符串数据的时候,大家肯定会想到使用 Newtonsoft.Json 去序列化(SerializeObject)和反序列化(DeserializeObject)一个对象。

使用 SerializeObject 的示例:

 1 A a = new A();
 2 a.age = 11;
 3 a.name = "Jack";
 4 B b = new B();
 5 b.sex = "Man";
 6 //b.money = 12;
 7 a.B = b;
 8 string str = Newtonsoft.Json.JsonConvert.SerializeObject(a);
 9 
10 输出结果:{"age": 11, "name": "Jack", "B": {"sex": "Man", "money": ""}}

使用 DeserializeObject 的示例:

1 string jsonStr = @"{"age": 11, "name": "Jack", "B": {"sex": "Man", "money": ""}}";
2 var a = Newtonsoft.Json.JsonConvert.DeserializeObject<A>(jsonStr);
3 
4 结果:a.age = 11;.......

好了,言归正传,如何使用 dynamic 去解析一个Json字符串呢?

1 string jsonStr = "{\"data\": {\"ssoToken\": \"70abd3d8a6654ff189c482fc4842468c\",\"account\":\"admin\",\"userType\":\"platformAdmin\",\"realName\": \"超级管理员\",\"sex\": 0,\"sexName\":\"男\",\"email\":\"alina_dong@163.com\",\"mobile\":\"15120757948\",\"createdDt\": \"2013-08-16 00:00:00\",\"updatedDt\": \"2014-12-10 00:00:00\" },\"isSuccess\": true}"; 
2 var loginInfo = JsonConvert.DeserializeObject<dynamic>(jsonStr); 
3 var user = loginInfo.data;
4 string ssoToken = user.ssoToken;
5 string account = user.account;

这样,不用创建loginInfo,user照样能解析JSON,而且不会因为那边增加字段报错啦。

陶陶的兔二,与你分享...

使用 dynamic 标记解析JSON字符串