Json to JObject转换的使用方法
类名 | 说明 |
JObject |
用于操作JSON对象 |
JArray |
用语操作JSON数组 |
JValue |
表示数组中的值 |
JProperty |
表示对象中的属性,以"key/value"形式 |
JToken
|
用于存放Linq to JSON查询后的结果
|
使用Linq to JSON
1.查询
首先准备Json字符串,是一个包含员工基本信息的Json
string json = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29}] }";
//将json转换为JObject JObject jObj = JObject.Parse(json); //通过属性名或者索引来访问,仅仅是自己的属性名,而不是所有的 JToken ageToken = jObj["Age"]; Console.WriteLine(ageToken.ToString());
②获取该员工同事的所有姓名
//将json转换为JObject JObject jObj = JObject.Parse(json); var names=from staff in jObj["Colleagues"].Children() select (string)staff["Name"]; foreach (var name in names) Console.WriteLine(name);
"Children()"可以返回所有数组中的对象
转自 增删改成都有,可以反复观看
增加几个平常用到的实例
// 一个JAarry 数组的类型
[{"SKU":"001X","SN":""},{"SKU":"00020","SN":""},{"SKU":"00099","SN":""},{"SKU":"7-M03910","SN":"049E"}]
var skus = new JArray(items.Select(l => new JObject { new JProperty("Sku", l.Element("itemCode").Value), new JProperty("SN",l.Element("serialNo").Value), })); var obj = new JObject { {"Head", new JObject { { "TransCode", "X1008" } } }, {"Body", new JObject { { "DeliveryDateTime", code4 }, { "SNs", skus }//这里没有层级关系 } } };
构造层级的JObject
var Orderline = new JArray(so.body.detail.Select(l => new JObject
{
new JProperty("itemCode", l.PartNo),
new JProperty("itemId", ""),
new JProperty("planQty", l.GoodsNumber)
}));
//封装xml var obj = new JObject { {"?xml",new JObject{ {"@version","1.0" }, {"@encoding","utf-8"}} }, { "request", new JObject{ {"deliveryOrder", new JObject { {"订单号",so.body.OrderSN }, {"senderInfo", new JObject{ { "city", city }, { "detailAddress", detailAddress }, } }, {"receiverInfo", new JObject{ { "city",so.body.City }, { "detailAddress", so.body.Address }, } }, {"customProps", new JObject{ { "insuranceMoney", "" }, { "consignee", "" }, } }, {"remark","" } } }, { "orderLines",new JObject{{ "orderLine", Orderline } } }//这里是有个层级关系的,orderLines下是orderline的集合 } } };
人各有命,上天注定,有人天生为王,有人落草为寇。脚下的路,如果不是你自己的选择,那么旅程的终点在哪,也没人知道。你会走到哪,会遇到谁,都不一定。