1. 程式人生 > 實用技巧 >JObject、JArray對JSON操作

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}");//根據路徑查詢