Search for a nested value inside of a JSON.net object in C#

后端 未结 3 1423
旧时难觅i
旧时难觅i 2020-12-10 07:33

I\'ve got a JSON stream coming back from a server, and I need to search for a specific value of the node \"ID\" using JSON.net to parse the data. And I can almost make it wo

相关标签:
3条回答
  • 2020-12-10 07:51

    Simply write a recursive function:

    private Thing FindThing(Thing thing, string name)
    {
        if (thing.name == name)
            return thing;
        foreach (var subThing in thing.childFolders.Concat(thing.childComponents))
        {
            var foundSub = FindThing(subThing, name);
            if (foundSub != null)
                return foundSub;
        }
        return null;
    }
    
    class RootObject
    {
        public Thing data { get; set; }
    }
    
    class Thing
    {
        public int id { get; set; }
        public string name { get; set; }
        public List<Thing> childFolders { get; set; } = new List<Thing>();
        public List<Thing> childComponents { get; set; } = new List<Thing>();
    }
    

    And using it:

    var obj = JsonConvert.DeserializeObject<RootObject>(jsonString);
    var result = FindThing(obj.data, "route3");
    
    0 讨论(0)
  • 2020-12-10 08:04

    My ultimate goal is to be able to search for "route3" and get back 19007

    You can use linq and Descendants method of JObject to do it:

    var dirs = JObject.Parse(json)
                .Descendants()
                .Where(x=>x is JObject)
                .Where(x=>x["id"]!=null && x["name"]!=null)
                .Select(x =>new { ID= (int)x["id"], Name = (string)x["name"] })
                .ToList();
    
    var id = dirs.Find(x => x.Name == "route3").ID;
    
    0 讨论(0)
  • 2020-12-10 08:11

    You can use the SelectToken or SelectTokens functions to provide a JPath to search for your desired node. Here is an example that would provide you the route based on name:

    JObject.Parse(jsonData)["data"].SelectToken("$..childComponents[?(@.name=='route3')]")
    

    You can find more documentation on JPath here

    0 讨论(0)
提交回复
热议问题