• 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}");//根据路径查找
  • 相关阅读:
    1-15-2-RAID1 企业级RAID磁盘阵列的搭建(RAID1、RAID5、RAID10)
    1-15-1 RAID磁盘阵列的原理和搭建
    伪随机数算法(一)
    Swing---WindowConstants
    cmd_ping命令
    开灯问题
    freopen()函数
    Beginning Python Chapter 3 Notes
    Beginning Python Chapter 2 Notes
    String | StringBuffer | StringBuilder 比较
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/12659937.html
Copyright © 2020-2023  润新知