-
using Newtonsoft.Json.Linq;
引入前辈的原网址:http://www.cnblogs.com/Sky-cloudless/archive/2012/04/24/2467936.html
1:根据简单的json字符串创建一个JObject对象。
-
,
-
-
JObject jo=new JObject();
-
jo.Add(new JProperty("name", "Tom"));
-
jo.Add(new JProperty("age", "15"));
-
-
-
JObject jo2=new JObject(new JProperty("name", "Tom"),new JProperty("age", "15"));
以上两种方式根据简单的json字符串创建了json对象.
2:根据模板对JArray数组的创建
-
-
JArray ja=new JArray();
-
ja.Add(new JValue("15252183408"));
-
ja.Add(new JValue("18749495008"));
3:需求:建一个关于学生的JObject对象,这个学生有姓名,年龄,电话(2个)
-
-
-
-
JObject jo=new JObject(new JProperty("name", "Tom"),new JProperty("age", "15"));
-
JArray ja=new JArray();
-
ja.Add(new JValue("15252183408"));
-
ja.Add(new JValue("18749495008"));
-
jo.Add(new JProperty("phone",ja.ToString()));
4:按模板构建json对象
-
{
-
"TeamName":".NET-a组",
-
"Dept":"计科2班",
-
"Mannager":"张二蛋",
-
"Member":[
-
{"NAME":"tOM","AGE":"15","PHONE":["15225183408","18749495008"]},
-
{"NAME":"tAKIM","AGE":"16","PHONE":["15225183128","18749495003"]}
-
-
]
-
}
5:根据模板,读取json对象的对应字段
-
{
-
"message":
-
{
-
"PRODNAME": "精谛果蔬原汁机",
-
"PRESENTSCODE": "ZP330006",
-
"POINT": null,
-
"SPRICE": null,
-
"PRESENTID": "ZP330006",
-
"PRICEFORNORMAL": "2680",
-
"GETPOINT": 1398,
-
"PRODTYPE": "0",
-
"USEPOINT": 0,
-
"BENEFIT": 100,
-
"SCODE": "JDGSYZJ",
-
"TRANMODE": null,
-
"PRESENTNUM": 1,
-
"PRESENTNAME": "金彪马陶瓷刀",
-
"UNITPRICE": 1398,
-
"SPEC":
-
[
-
{
-
"SPEC3": null,
-
"SPEC2": "JD--12",
-
"STORENUM": 64,
-
"SPEC1": "白色"
-
}
-
],
-
"PRODID": "330006",
-
"INPRICE": 908
-
}
-
}
以上信息是一个"商品明细接口"返回的一个货号为330066商品的基本信息,我们需要读取库存字段,名称字段,价格字段.\
我们可以把上面的内容转化为一个JObject对象,然后就可以读取了;如下代码:
-
{
-
WebRequest wr = WebRequest.Create("http://xxxxxxxxxxxxxxxx:1218/product/proid?proid=330066");//URI
-
WebResponse wres = wr.GetResponse();
-
Stream stream = wres.GetResponseStream();
-
StreamReader sr = new StreamReader(stream);
-
string strJson = sr.ReadToEnd();
-
JObject jo = JObject.Parse(strJson);
-
string message=jo["message"].ToString();
-
JObject jo_msg = JObject.Parse(message);
-
-
string store_count = "0";
-
string price = jo_msg["UNITPRICE"].ToString();
-
-
string pro_name = jo_msg["PRODNAME"].ToString();
-
-
-
JArray ja = JArray.Parse(jo_msg["SPEC"].ToString());
-
int ja_length = ja.Count();
-
for (int i = 0; i < ja_length;i++ )
-
{
-
JObject jo_temp =JObject.Parse(ja[i].ToString());
-
store_count = jo_temp["STORENUM"].ToString();
-
}
-
}
原理就是"层层剥取",其实这些就算是linq to json的部分功能了,在后面我会说使用Linq对json的查询.