JObject、JArray对JSON操作
增删改查:
复制代码
var cardJson = "['身份证','银行卡','门禁卡']";
var cardJArray = JArray.Parse(cardJson);
var p = new Person { Name="fan",Age=12,Dog=new Dog { Name="奶牛"} };
var pJson = JsonConvert.SerializeObject(p);
JObject jobj = JObject.Parse(pJson);
//添加属性
jobj["NickName"] = "fan";
jobj["Wifes"] = new JArray("rose", "lisa");
((JArray)jobj["Wifes"]).Add( "july");
jobj["Cards"] = cardJArray;
//修改属性
jobj["Name"] = "li";
jobj["Age"] = 9;
jobj["Dog"]["Name"] = "阿黄";
((JArray)jobj["Wifes"])[0] = "roses";
//插入属性
jobj.Property("Name").AddBeforeSelf(new JProperty("ID", 1));
//删除属性
jobj.Property("Age").Remove();
((JArray)jobj["Wifes"])[2].Remove();
//查找
//遍历属性
var props = jobj.Children().Values();
foreach (var prop in props)
{
if (!(prop is JObject) && !(prop is JArray))
{
Console.WriteLine(prop.ToString());
}
}
//遍历数组
var cardList = ((JArray)jobj["Cards"]);
foreach (var card in cardList)
{
Console.WriteLine(card.ToString());
}
//强类型读取
Console.WriteLine(jobj.Value<int>("ID"));
var p2 = jobj.ToString();
复制代码
对象->JObject->JSON:
复制代码
var json = new JObject(
new JProperty("status", result.Status.ToString()),
new JProperty("results", new JObject(result.Entries.Select(pair =>
new JProperty(pair.Key, new JObject(
new JProperty("status", pair.Value.Status.ToString()),
new JProperty("description", pair.Value.Description),
new JProperty("data", new JObject(pair.Value.Data.Select(
p => new JProperty(p.Key, p.Value))))))))));
var str = json.ToString();
复制代码
JObject合并:
jObj.Merge(JObject.Parse(userTranslate.ValueJSON));
JObject查找:
jObject.SelectToken($".{path}");//根据路径查找