假如我们得到了一个json的数据:json===》 {"Head":{"TransCode":"X1009","TransId":"20190514145005iQXk"},"Body":{"OrderSN":"95131406006","WHSE":"aaaaa","SNs":[{"SN":"HCMPFD000621"},{"SN":"1212122"}]}}
类似这样。我们要取出来里面特定的值,而且,SNs还是一个集合。
方法如下:
string OrderSn = json["Body"]["OrderSN"].ToString();
string WHSE = json["Body"]["WHSE"].ToString();
string SNs = json["Body"]["SNs"].ToString();
SNs是一个集合,怎么取出来呢:
将json字符串解析为JToken,JObject是JToken的父类,直接使用JToken比较好用
dynamic Sns =JToken.Parse(SNs) as dynamic
for (int i = 0; i < Sns.Count; i++)//获取备注里的SN
{
if (Sns[i].SN.ToString() != "")
{
str += Sns[i].SN.ToString() + ",";
}
}
这样子就可以循环出来里面的值了。
1 HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 2 string response = string.Empty; 3 using (StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream())) 4 response = reader.ReadToEnd(); 5 6 var j = JObject.Parse(response); 7 string shop_name = j["Success"]["items"]["item"][0]["shop_name"].ToString();//独一味日化旗舰店、、、一层层的层级关系
{
"Success": {
"total_results": "1",
"items": {
"item": [{
"shop_name": "独一味日化旗舰店",
"serial_num": "",
"order_channel": "直营网店",
"updatetime": "",
"总数量": "3739",
"maxrowver": "",
"tid_item": [{
"storage_id": "1",
"tid": "S17fdgfgfg0349",
"pro_detail_code": "191",
"book_inventory": "-5.000",
"store_location": "",
"pro_type": "原始产品"
}, {
"storage_id": "1",
"tid": "S1712220000349",
"pro_detail_code": "152",
"book_inventory": "-4.000",
"store_location": "",
"pro_type": "原始产品"
}]
}]
}
}
}
上面这个是其他的厂商返回的一个Json格式的数据,现在可以是Json嵌套的还挺多,其中的一个项次还有数组,现在就是把这些数据捞出来存下来。
var j = JObject.Parse(response);
//这个就是主干的值
string shop_name = j["Success"]["items"]["item"][0]["shop_name"].ToString();//独一味日化旗舰店
string tid_item = j["Success"]["items"]["item"][0]["tid_item"].ToString();
//下面是获取数组的名细可以取出来值
JArray jArray = JArray.Parse(tid_item);
for (int i = 0; i < jArray.Count; i++)
{
JObject jdata = (JObject)jArray[i];
string pro_detail_code = jdata["pro_detail_code"].ToString();
}
//将数据动态插入到数组中去
JArray jArray = JArray.Parse(tid_item); JArray arr = new JArray(); for (int i = 0; i < jArray.Count; i++) { JObject obj = new JObject(); JObject jdata = (JObject)jArray[i]; obj["linenum"] = jdata["cost_price"].ToString(); obj["sku"] = jdata["sell_price"].ToString(); obj["qty"] = jdata["original_price"].ToString(); obj["inventoryname"] = jdata["sys_price"].ToString(); obj["price"] = jdata["product_name"].ToString(); arr.Add(obj); } var rss = new JObject { {"Head",new JObject { {"TransCode","X1009" }, {"TransId",1212} } }, { "Body", new JObject { {"orderno", "orderno" }, {"billto","billto"}, {"shipto", "shipto"}, {"workid", "workid"}, {"tocity", "tocity"}, {"Address", "Address"}, {"Contact", "Contact"}, {"Tel", "Tel"}, {"detail", arr } } } };