C#json 解析
Json样例一:
string jsonText=
{Code":0,"Message":"成功","Data":{"BoardProvinceName":"上海","BoardCityName":"上海","BoardDetailAddress":"普陀区怒江北路449弄8号C5","CourierName":"15601804660","CourierMobile":"15601804660","CargoNo":89,"BoardNo":3,"BoxNo":2,"DoorNo":3,"ExpressNo":"333333","CargoPassword":null,"Size":3,"Status":2,"StoreTime":"\/Date(1406772770183)\/","ExtractionTime":"\/Date(1415185496877)\/","CustomerMobile":"15601804660","CourierPId":"321323198902082117"}}}
JObject jo = JObject.Parse(jsonText); string strCode= jo["Code"].ToString();//Code:0
string ddaf = GetJsonValue(jo.Children(), "BoardDetailAddress");//BoardDetailAddress:普陀区怒江北路449弄8号C5
=====================================================================
不带==》 “[”
string jsonData = "{\"name\":\"lily\",\"age\":23,\"addr\":{\"city\":\"guangzhou\",\"province\":\"guangdong\"}}";
JObject jsonObj = JObject.Parse(jsonData);
string strname = jsonObj["name"].ToString();
string strprovince = GetJsonValue(jsonObj.Children(), "province");
=====================================================================
类:
public static string GetJsonValue(JEnumerable<JToken> jToken, string key) { IEnumerator enumerator = jToken.GetEnumerator(); while (enumerator.MoveNext()) { JToken jc = (JToken)enumerator.Current; if (jc is JObject || ((JProperty)jc).Value is JObject) { return GetJsonValue(jc.Children(), key); } else { if (((JProperty)jc).Name == key) { return ((JProperty)jc).Value.ToString(); } } } return null; }
=================================================================================
带==》 “[”
string jsonText ="{'name':'test','phone':'18888888888','image':[{'name':'img1','data':'data1'},{'name':'img2','data':'data2'},{'name':'img3','data':'data3'}]}"; string jsonText1 = "{'name':'test','phone':'18888888888','image':[{'name':'img1','data':'data1'}]}"; JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText); string zone = jo["name"].ToString(); string zone_en = jo["phone"].ToString(); JArray jar = JArray.Parse(jo["image"].ToString()); string c = zone; string d = zone_en; for (var i = 0; i < jar.Count; i++) { JObject j = JObject.Parse(jar[i].ToString()); string a = j["name"].ToString(); string b = j["data"].ToString(); }
多层嵌套
string jsonData1 = "{\"addr\":[{\"city\":\"guangzhou\",\"province\":\"guangdong\"},{\"city\":\"guiyang\",\"province\":\"guizhou\"}]}"; JObject jsonObj1 = JObject.Parse(jsonData1); JArray jar1 = JArray.Parse(jsonObj1["addr"].ToString()); JObject j0 = JObject.Parse(jar1[0].ToString()); JObject j1 = JObject.Parse(jar1[1].ToString()); string city1 = j0["city"].ToString(); //guangzhou string city2 = j0["city"].ToString(); //guiyang
以上亲测可用
转载 请注明原文地址并标明转载:http://www.cnblogs.com/laopo
商业用途请与我联系:lcfhn168@163.com