Parse a JSON string using the dynamic tag, dynamicjson
1 string jsonStr = "{\" data \ ": {\" ssoToken \ ": \" 70abd3d8a6654ff189c482fc4821368c \ ", \" account \ ": \" admin \", \ "userType \": \ "platformAdmin \", \ "realName \": \ "Super Administrator \", \ "sex \": 0, \ "sexName \": \ "male \", \ "email \": \ "alina_dong@163.com \", \ "mobile \": \ "15120757948 \", \ "createdDt \": \ "00:00:00 \", \ "updatedDt \": \ "00:00:00 \" },\ "isSuccess \": true }";
When the. Net Program receives this JSON string, you will surely think of using Newtonsoft. Json to serialize (SerializeObject) and deserialize (DeserializeObject) an object.
Example of using SerializeObject:
1 A a = new A (); 2. age = 11; 3. name = "Jack"; 4 B B = new B (); 5 B. sex = "Man"; 6 // B. money = 12; 7. B = B; 8 string str = Newtonsoft. json. jsonConvert. serializeObject (a); 9 10 output result: {"age": 11, "name": "Jack", "B": {"sex": "Man ", "money ":""}}
DeserializeObject example:
1 string jsonStr = @ "{" age ": 11," name ":" Jack "," B ": {" sex ":" Man "," money ": ""} "; 2 var a = Newtonsoft. json. jsonConvert. deserializeObject <A> (jsonStr); 3 4 Results:. age = 11 ;.......
Now let's get down to the point. How can we use dynamic to parse a Json string?
1 string jsonStr = "{\" data \ ": {\" ssoToken \ ": \" 70abd3d8a6654ff189c482fc4821368c \ ", \" account \ ": \" admin \", \ "userType \": \ "platformAdmin \", \ "realName \": \ "Super Administrator \", \ "sex \": 0, \ "sexName \": \ "male \", \ "email \": \ "alina_dong@163.com \", \ "mobile \": \ "15120757948 \", \ "createdDt \": \ "00:00:00 \", \ "updatedDt \": \ "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;
In this way, you do not need to create loginInfo. the user can parse JSON as well, and no error will be reported because of the added fields.
Tao's rabbit II, share with you...