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 的示例:
A a = new A();
a.age = ;
a.name = "Jack";
B b = new B();
b.sex = "Man";
//b.money = 12;
a.B = b;
string str = Newtonsoft.Json.JsonConvert.SerializeObject(a); 输出结果:{"age": , "name": "Jack", "B": {"sex": "Man", "money": ""}}
使用 DeserializeObject 的示例:
string jsonStr = @"{"age": 11, "name": "Jack", "B": {"sex": "Man", "money": ""}}";
var a = Newtonsoft.Json.JsonConvert.DeserializeObject<A>(jsonStr); 结果:a.age = ;.......
好了,言归正传,如何使用 dynamic 去解析一个Json字符串呢?
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}";
var loginInfo = JsonConvert.DeserializeObject<dynamic>(jsonStr);
var user = loginInfo.data;
string ssoToken = user.ssoToken;
string account = user.account;
这样,不用创建loginInfo,user照样能解析JSON,而且不会因为那边增加字段报错啦。