1 string jsonStr = "{\"data\": {\"ssoToken\": \"70abd3d8a6654ff189c482fc4842468c\",\"account\":\"admin\",\"userType\":\"platformAdmin\",\"realName\": \"超級管理員\",\"sex\": 0,\"sexName\":\"男\",\"email\":\"[email protected]\",\"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\":\"[email protected]\",\"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,而且不會因為那邊增加字段報錯啦。
陶陶的兔二,與你分享...