类名 | 说明 |
JObject |
用于操作JSON对象 |
JArray |
用语操作JSON数组 |
JValue |
表示数组中的值 |
JProperty |
表示对象中的属性,以"key/value"形式 |
JToken |
用于存放Linq to JSON查询后的结果 |
测试json
{}对应的是JObject,而[]对应的是JArray。
json解析:
工程中引入NuGet包,
{ "Data":[ {"AA":"aa1","BB":"bb1"}, {"AA":"aa2","BB":"bb2"} ] }
如果是这种简单的json,可以直接建立相应的model,反序列化为对象即可。
class Top { public List<Data> Data { get; set; } } class Data { public string AA { get; set; } public string BB { get; set; } } //整体是一个Top类,data的数组是Data类, var top = JsonConvert.DeserializeObject<Top>(str_Json); var data = top.Data.ToList<Data>();
对于复杂的json,建model解析就太繁琐了。
{ "status": 0, "message": "query ok", "result": { "address": "北京市海淀区彩和坊路海淀西大街74号", "address_component": { "province": "北京市", "city": "北京市", "district": "海淀区", "street": "彩和坊路", "street_number": "海淀西大街74号" }, "pois": [ { "id": "3629720141162880123", "title": "中国技术交易大厦", "address": "北京市海淀区北四环西路66号", "category": "房产小区;商务楼宇", "location": { "lat": "39.984122", "lng": "116.307484" }, "_distance": "3.6" }, { "id": "2845372667492951071", "title": "中国技术交易大厦A座", "address": "北京市海淀区北四环西路66号", "category": "房产小区;商务楼宇", "location": { "lat": "39.984273", "lng": "116.307577" }, "_distance": "15.2" } ] } }
class location { public string lat { get; set; } public string lng { get; set; } } class pois { public string id { get; set; } public string title { get; set; } public string address { get; set; } public string category { get; set; } public location location { get; set; } public string _distance { get; set; } } //因为整体是一个对象所以解析为jobject,dd["xx"]获取对象的属性值,path表达式 var dd = JObject.Parse(str_Json); //获取属性值 var oo = dd["message"]; //获取数组 var rr = JArray.Parse(dd["result"]["pois"].ToString()); //将数据对象化 var ii = rr.ToObject<List<pois>>(); //数组第一个元素 var gg = ii[0].location;
[ { "id": "3629720141162880123", "title": "中国技术交易大厦", "address": "北京市海淀区北四环西路66号", "category": "房产小区;商务楼宇", "location": { "lat": "39.984122", "lng": "116.307484" }, "_distance": "3.6" }, { "id": "2845372667492951071", "title": "中国技术交易大厦A座", "address": "北京市海淀区北四环西路66号", "category": "房产小区;商务楼宇", "location": { "lat": "39.984273", "lng": "116.307577" }, "_distance": "15.2" } ]
//因为整体是个数组,就解析为数组 var rr = JArray.Parse(str_Json); //将数据对象化 var ii = rr.ToObject<List<pois>>(); //数组第一个元素 var gg = ii[0].location;
json生成
//对象序列化json串,单个对象序列化成Json对象{} list为数组[{}] //var json = new Data() { AA = "", BB = "" }; var json = new List<Data>() { new Data() { AA="11",BB="11"}, }; var dd = JsonConvert.SerializeObject(json);
对json创建,修改等参考:https://www.cnblogs.com/usharei/archive/2012/04/24/2467578.html