使用LINQ在嵌套JSON/JTOKEN中获取价值 [英] Get value in Nested JSON/JTOKEN using LINQ

查看:259
本文介绍了使用LINQ在嵌套JSON/JTOKEN中获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是LINQ查询的新手,并且想知道是否可以通过LINQ查询实现我要实现的目标.

I am new to LINQ queries and would like to know if what I am trying to achieve is possible via LINQ query.

因此,我有一个JSON文档,如下所示.

So, I have a JSON doc as below.

我正在尝试获取与"$ type" 匹配的所有值,并向我返回目录路径和$ type的值.

I am trying to get all the values that match the "$type" and return me the directory path and the value for $type.

我知道执行此操作的交互式方式,但是LINQ似乎是首选,并且应该很容易实现.

I know an interactive way of doing this but it seems LINQ is preferred and supposed to be easy to get this.

{
   "$type":"type1",
   "title":"US version",
   "_object1":[
      {
         "$type":"type2",
         "rootModule":{
            "id":"page",
            "modules":[
               {
                  "id":"header",
                  "$type":"module-header"
               },
               {
                  "id":"footer",
                  "$type":"module-footer"
               }
            ]
         }
      },
      {
         "$type":"type2",
         "_id":"ab134"
      },
      {
         "$type":"type3",
         "_id":"ab567"
      }
   ],
   "_object2":[
      {
         "$type":"module1",
         "constraintsId":"page"
      },
      {
         "name":"header1 1",
         "nestedobject":{
            "$type":"nestedobject-type",
            "dataBinder":{
               "id":"ab244"
            }
         }
      }
   ]
}

推荐答案

谢谢大家

我能够得到如下列表:

    var root = (JContainer)JToken.FromObject(document, CommonSerializerSetting.GetCommonSerializer());
    var descendant = "$type";
    var query = root

        // Recursively descend the JSON hierarchy
        .DescendantsAndSelf()

        // Select all properties named descendant
        .OfType<JProperty>()
        .Where(p => p.Name == descendant)

        // Select their value
        .Select(p => p.Value);

这篇关于使用LINQ在嵌套JSON/JTOKEN中获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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