The use of C# JArray and JObject

STEP1、using Newtonsoft.Json.Linq;

 

STEP2 How to get an attribute (node) value in json, delete it, add it

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//2.1 数组用JArray加载
 
string  jsonText =  "[{'a':'aaa','b':'bbb','c':'ccc'},{'a':'aa','b':'bb,'c':'cc'}]" ;  
 
var  mJObj = JArray.Parse(jsonText);
 
//需求,删除列表里的a节点的值为'aa'的项
 
IList<JToken> delList =  new  List<JToken>();  //存储需要删除的项
 
foreach  ( var  ss  in  mJObj )   //查找某个字段与值
{
if (((JObject) ss)[ "a" ]== "aa" )
 
delList .add(ss);
}
 
foreach  ( var  item  in  delList )   //移除mJObj  在delList 里的项
{
 
mJObj .remove(item); 
}
 
 
 
//2.2 非数组用JObject加载 (这里主要以这个为例子)
 
string  jsonText =  "[{'a':'aaa','b':'bbb','c':'ccc'}]" ;  
 
var  mJObj = JObject.Parse(jsonText t);
 
mJObj.Add()  //新增,没试过
 
var  v1=mJObj[a].ToString()   //得到'aaa'的值

  

The above examples can be used interactively and flexibly

 

Note, JArray can only be used to find the object of the indexed item. To find the object, you need to convert it to JObject, and then find the corresponding property value.

 

其他写法补充

1、属性下嵌套json (非数组)遍历其包含的属性列表

var xx = ((mJObj["dim"])).Children().Values(); 

foreach (var item in xx)
{
var dimID = ((JObject) item)["id"];

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325559189&siteId=291194637