zoukankan      html  css  js  c++  java
  • 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}");//根据路径查找

  • 相关阅读:
    关于分工协作
    SQL分类后每类随机抽取
    新浪微群抢票
    to learn softwarelist
    大厂程序员教你如何学习C++(内附学习资料)
    干货|大厂程序员来讲一下互联网公司技术面试的流程以及注意事项
    程序员要如何写简历(附简历模板)
    laravel项目拉取下来安装,node.js库安装
    laravelhas方法查看关联关系
    laravel框架少见方法详解
  • 原文地址:https://www.cnblogs.com/owenzh/p/13408758.html
Copyright © 2011-2022 走看看