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

后端 未结 3 1426
旧时难觅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 childFolders { get; set; } = new List();
        public List childComponents { get; set; } = new List();
    }
    

    And using it:

    var obj = JsonConvert.DeserializeObject(jsonString);
    var result = FindThing(obj.data, "route3");
    

提交回复
热议问题