Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

c# - Get value in Nested JSON/JTOKEN using LINQ

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"
            }
         }
      }
   ]
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...