使用Linq,JSON.NET,C#查询JSON嵌套数组 [英] Querying JSON Nested Arrays with Linq, JSON.NET, C#

查看:68
本文介绍了使用Linq,JSON.NET,C#查询JSON嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇文章旨在问一个与我最近的其他帖子有关的更直接的问题(

This post is an effort to ask a more direct question related to my other recent post (Picking Out Simple Properties from Hierarchical JSON Part II):

给出嵌套的JSON文档,例如:

Given nested JSON document, as such:

{
  "Array1": {
    "Array1A": [
      { "Item1": "1" },
      { "Item2": "2" },
      { "Item3": "3" }
    ],
    "Array1B": [
      { "Item1": "1" },
      { "Item2": "2" },
      { "Item3": "3" }
    ]
  },
  "Array2": {
    "Array2A": [
      { "Item1": "1" },
      { "Item2": "2" },
      { "Item3": "3" }
    ]
  },
  "Array3": {
    "Array3A": [
      { "Item1": "1" },
      { "Item2": "2" },
      { "Item3": "3" }
    ],
    "Array3B": [
      { "Item1": "1" },
      { "Item2": "2" },
      {
        "Array3B1": [
          { "Item1": "1" },
          { "Item2": "2" },
          { "Item3": "3" }
        ]
      }
    ],
    "Array3C": [
      { "Item1": "1" },
      { "Item2": "2" },
      { "Item3": "3" }
    ]
  }
}

(注意:以上已通过JSLint验证.)

(Note: Above was validated with JSLint.)

请注意,JSON是动态的-我事先不知道会有多少个数组,或者数组嵌套的深度.

Notice that the JSON is dynamic--I do not know in advance how many arrays there will be or how deep the arrays will nest.

目标: 我的目标是在List<JObject>对象中表示每个数组(即Array1,Array2,Array3,Array3A,Array3B和Array3B1).列表中的每个项目都是JProperty对象的集合,其中包含该数组的字符串属性.由于List本身并不建模分层数据,因此我需要向引用该数组的父级的每个List<JObject>项目添加一个综合属性.因此,Array1的父级是一个空字符串. Array2是Array1,Array3是Array2,Array3A是Array3,Array3B是Array3,Array 3B1是Array3B ...

Goal: My goal is to represent each array (that is, Array1, Array2, Array3, Array3A, Array3B, and Array3B1) in a List<JObject> object. Each item in the list will be a collection of JProperty objects containing that array's string properties. Because the List doesn't itself model hierarchical data, I would need to add a synthetic property to each List<JObject> item that references the parent of that array. Thus, the parent of Array1 is an empty string; Array2 is Array1, Array3 is Array2, Array3A is Array3, Array3B is Array3, and Array 3B1 is Array3B...

问题: 1.如何使用C#Linq创建一个如下所示的List<JObject>对象:

Question: 1. How can I use C# Linq to create a List<JObject> object that looks like this:

list[0]: 
{"Name":"Array1","Parent":""}

list[1]:
{"Name":"Array1A","Item1":"1","Item2":"2","Item3":"3","Parent":"Array1"}

list[2]:
{"Name":"Array1B","Item1":"1","Item2":"2","Item3":"3","Parent":"Array1"}

list[3]:
{"Name":"Array2","Parent":""}

list[4]:
{"Name":"Array2A","Item1":"1","Item2":"2","Item3":"3","Parent":"Array2"}

list[5]:
{"Name":"Array3","Parent":""}

list[6]:
{"Name":"Array3A","Item1":"1","Item2":"2","Item3":"3","Parent":"Array3"}

list[7]:
{"Name":"Array3B","Item1":"1","Item2":"2","Parent":"Array3"}

list[8]:
{"Name":"Array3B1","Item1":"1","Item2":"2","Item3":"3","Parent":"ArrayB"}

list[9]:
{"Name":"Array3C","Item1":"1","Item2":"2","Item3":"3","Parent":"Array3"}

请注意:

  • 每个List<JObject>仅包含字符串属性.
  • 在列表[7]处,缺少Item2之后的JSON令牌,因为它是一个数组.而是使用正确的父引用在list [8]中表示该项目.
  • Each List<JObject> contains only string properties.
  • At list[7], the JSON token after Item2 is missing because it's an array. Instead, that item is expressed in list[8] with the correct parent reference.

推荐答案

类似这样的事情:

List<JObject> list = 
    JObject.Parse(json)
           .Descendants()
           .Where(jt => jt.Type == JTokenType.Property && ((JProperty)jt).Value.HasValues)
           .Cast<JProperty>()
           .Select(prop =>
           {
               var obj = new JObject(new JProperty("Name", prop.Name));
               if (prop.Value.Type == JTokenType.Array)
               {
                   var items = prop.Value.Children<JObject>()
                                         .SelectMany(jo => jo.Properties())
                                         .Where(jp => jp.Value.Type == JTokenType.String);
                   obj.Add(items);
               }
               var parentName = prop.Ancestors()
                                    .Where(jt => jt.Type == JTokenType.Property)
                                    .Select(jt => ((JProperty)jt).Name)
                                    .FirstOrDefault();
               obj.Add("Parent", parentName ?? "");
               return obj;
           })
           .ToList();

提琴: https://dotnetfiddle.net/FMxzls

如果您不熟悉 LINQ-to-JSON ,它是如何分解的:

If you're not that familiar with LINQ-to-JSON, here's how it breaks down:

  1. 将json字符串解析为JObject

  1. Parse the json string into a JObject

JObject.Parse(json)

  • 从该JObject中获取其所有后代JTokens

  • From that JObject, get all of its descendant JTokens

           .Descendants()
    

  • 仅将该列表过滤为仅包含其子元素的JProperty

  • Filter that list to only JProperties whose values have children

           .Where(jt => jt.Type == JTokenType.Property && ((JProperty)jt).Value.HasValues)
    

  • 将JTokens转换为JProperty,以使其在下一步中更易于使用

  • Cast the JTokens to JProperties to make them easier to work with in the next step

           .Cast<JProperty>()
    

  • 现在,对于我们选择的每个JProperty,将其转换如下:

  • Now, for each JProperty we selected, transform it as follows:

           .Select(prop =>
           {
    

  • 创建一个新的JObject并将JProperty的名称添加为新对象的Name属性

               var obj = new JObject(new JProperty("Name", prop.Name));
    

  • 如果JProperty的值是一个数组...

  • If the value of the JProperty is an array...

               if (prop.Value.Type == JTokenType.Array)
               {
    

  • 获取数组的所有直接子对象,即JObjects

  • Get all the direct children of the array which are JObjects

                   var items = prop.Value.Children<JObject>()
    

  • 从那些JObjects中获取所有JProperties

  • From those JObjects, get all the JProperties

                                         .SelectMany(jo => jo.Properties())
    

  • 过滤那些JProperty,使其仅包括那些值为字符串的JProperty.

  • Filter those JProperties to include only the ones whose values are strings)

                                         .Where(jp => jp.Value.Type == JTokenType.String);
    

  • 将这些项目JProperties添加到我们之前创建的新JObject中

  • Add these item JProperties to the new JObject we created earlier

                    obj.Add(items);
                }
    

  • 接下来,找到当前JProperty的第一个祖先JProperty并获取其名称

  • Next, find the first ancestor JProperty of the current JProperty and get its name

                var parentName = prop.Ancestors()
                                     .Where(jt => jt.Type == JTokenType.Property)
                                     .Select(jt => ((JProperty)jt).Name)
                                     .FirstOrDefault();
    

  • 将父名称添加到我们正在构建的JObject中;如果没有父母,请使用空字符串

  • Add the parent name to the JObject we're are building; use an empty string if there was no parent

                obj.Add("Parent", parentName ?? "");
    

  • 继续下一个转换

  • Continue with the next transform

                return obj;
            })
    

  • 最后将我们构建的所有JObject放入列表中.

  • Lastly put all the JObjects we built into a list.

            .ToList();
    

  • 这篇关于使用Linq,JSON.NET,C#查询JSON嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆