原文:Json的动态解析

 最近在项目中需要动态解析json,但解析json的方式有很多,如何合理的解析就是我们需要考虑的问题?比如Newtonsoft.Json.Linq下提供的JToken、JObject等,Newtonsoft.Json下提供的JsonConvert。

JObject 用于操作json对象
JArray用于操作json数组
JValue表示数组的值
JProperty 表示对象中的属性,以"key/value"的形式
JToken用于存放Linq to Json查询后的结果

我们今天主要介绍不同解析方式适用的场景以及用法:

1、JObject

  JObject用于操作对象,若用它来解析其它类型的json会报Newtonsoft.Json.JsonReaderException。 

JObject jObject = new JObject();
jObject.Add(new JProperty("name", "caixukun"));
jObject.Add(new JProperty("skill", new JObject(new JProperty("id", 1), new JProperty("name", "撩妹"))));
Console.WriteLine(jObject.ToString());
结果:
{
"name": "caixukun",
  "skill": {
    "id": 1,
    "name": "撩妹"
  }

 2、JArray

  JArray用于操作数组,若用它来解析其它类型的json会报Newtonsoft.Json.JsonReaderException。 

JArray arr = new JArray();
arr.Add(new JValue(1));
arr.Add(new JValue(2));
arr.Add(new JValue(3));
Console.WriteLine(arr.ToString());
结果:
[
 1,
 2,
 3
]

3、JToken 

string json = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29}] }";
// 获取员工名称
JObject jObject = JObject.Parse(json);
var name = jObject.Value<string>("Name");
Console.WriteLine(name);
// 获取员工年龄
JToken jToken = jObject.SelectToken("Age");
Console.WriteLine(jToken.ToString());
// 获取同事信息
JToken jToken1 = jObject["Colleagues"];
Console.WriteLine(jToken1.ToString());
Console.WriteLine("=============================");
// 获取员工同事的所有姓名
var names = from staff in jToken1.Children()
            select (string)staff["Name"];
// var names = jObject.SelectToken("Colleagues").Select(p => p["Name"]).ToList();
foreach (var item in names)
{
    Console.WriteLine(item);
}
Console.WriteLine("=============================");
// 修改Jack的年龄
jObject["Age"] = 99;
Console.WriteLine(jObject.ToString());
// 修改同事Tome的年龄
jToken1[0]["Age"] = 45;
Console.WriteLine(jObject.ToString());
Console.WriteLine("=============================");
// Abel离职了
jObject["Colleagues"][1].Remove();
Console.WriteLine(jObject.ToString());
// 移除Jack的同事
jObject.Remove("Colleagues");
Console.WriteLine(jObject.ToString());
Console.WriteLine("=============================");
// Jack缺少部门信息
jObject["Age"].Parent.AddAfterSelf(new JProperty("Department", "总裁办"));
// 来了一个新员工Jerry
JObject linda = new JObject(new JProperty("Name", "Linda"), new JProperty("Age", "23"));
jObject.Add(new JProperty("Colleagues", new JArray() { linda }));
Console.WriteLine(jObject.ToString());

参考:https://www.cnblogs.com/klsw/p/5904573.html

02-10 06:16