今天在做Asp网站开发的时候接受到了一种下面这种样子的字符串:
1 "[2 {3 "mid": "123456",4 "nid": "321",5 "data": [6 {7 "mid": "1",8 "name": "111"9 },10 {11 "mid": "2",12 "name": "222"13 },14 {15 "mid": "3",16 "name": "333"17 },18 {19 "mid": "4",20 "name": "444"21 },22 {23 "mid": "5",24 "name": "555"25 }26 ]27 },28 {29 "mid": "123456",30 "nid": "321",31 "data": [32 {33 "mid": "1",34 "name": "111"35 },36 {37 "mid": "2",38 "name": "222"39 },40 {41 "mid": "3",42 "name": "333"43 },44 {45 "mid": "4",46 "name": "444"47 },48 {49 "mid": "5",50 "name": "555"51 }52 ]53 }54 ]"
查阅了资料发现 这种写法的字符串其实是一种Json数组,
Json数组格式为:[{"name1":"value","name2":"value"},{"name1":"value","name2":"value"}];
而由"{ }"包括着的是一个Json对象。
我们在开发中经常遇到的多是这两种格式的字符串。
对于一个json对象格式的字符串:
直接使用JObject job =JObject.Parse("....."),就可以转换为json对象;
然后使用 job["属性名"]的方式就可以取出其中一个一个的值。
由多个json对象组成的json数组格式的字符串:
第一步:将jsonArray格式字符串转换成JsonArray对象;
第二步:遍历JsonArray中的每一项(每一项都是一个Json对象);
第三步:和单个json对象的解析方式是一样的。
1 string hh ="[{"mid": "123456","nid": "321","data": [{"mid": "1","name": "111" },{"mid": "2","name": "222"}, {"mid": "3","name": "333" },{"mid": "4","name": "444"},{"mid": "5","name": "555" } ]},{"mid": "123456","nid": "321","data": [ {"mid": "1","name": "111" }, {"mid": "2","name": "222" }, {"mid": "3","name": "333"},{"mid": "4","name": "444" }, {"mid": "5", "name": "555" } ]}
]";3 JArray jArray = JArray.Parse(hh);4 foreach (var jj injArray)5 {6 //string job= jj.ToString();7 //JObject jObject=JObject.Parse(job);
8 JObject job =(JObject)jj;9 JArray datArray = JArray.Parse(job["data"].ToString());10 foreach (var item indatArray)11 {12 JObject jdata =(JObject)item;13 string aa = jdata["mid"].ToString();14 string bb = jdata["name"].ToString();15 }16 }
记录下来,以后遇见类似的需求希望能用到!