Get value in Nested JSON/JTOKEN using LINQ

断了今生、忘了曾经 提交于 2019-12-13 08:47:13

问题


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

So, I have a JSON doc as below.

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

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"
            }
         }
      }
   ]
}

回答1:


Thanks guys,

I was able to get the list as below:

    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);


来源:https://stackoverflow.com/questions/52376833/get-value-in-nested-json-jtoken-using-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!