How to do recursive descent of json using json.net?

前端 未结 5 1000
鱼传尺愫
鱼传尺愫 2020-11-30 08:48

I am trying to parse a json file using json.net. The file looks like this

{X:
   {
      Title:\"foo\",
      xxxx:xxxx
   }
}
{Y:
   {ZZ:
        {Title: \"         


        
5条回答
  •  感动是毒
    2020-11-30 09:28

    The code below should be pretty close to what you are looking for. I made the assumption that there is an outer array, and that arrays can appear anywhere in the hierarchy. (If this is not true, you can simplify the WalkNode method code a bit, but it should work either way.)

    using System;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
    namespace JsonRecursiveDescent
    {
        class Program
        {
            static void Main(string[] args)
            {
                string json =
                @"[
                    {
                        ""X"":
                        {
                            ""Title"":""foo"",
                            ""xxxx"":""xxxx""
                        }
                    },
                    {
                        ""Y"":
                        {
                            ""ZZ"":
                            {
                                ""Title"":""bar"",
                                ""xxxx"":""xxxx""
                            }
                        }
                    }
                ]";
    
                JToken node = JToken.Parse(json);
    
                WalkNode(node, n =>
                {
                    JToken token = n["Title"];
                    if (token != null && token.Type == JTokenType.String)
                    {
                        string title = token.Value();
                        Console.WriteLine(title);
                    }
                });
            }
    
            static void WalkNode(JToken node, Action action)
            {
                if (node.Type == JTokenType.Object)
                {
                    action((JObject)node);
    
                    foreach (JProperty child in node.Children())
                    {
                        WalkNode(child.Value, action);
                    }
                }
                else if (node.Type == JTokenType.Array)
                {
                    foreach (JToken child in node.Children())
                    {
                        WalkNode(child, action);
                    }
                }
            }
    
        }
    }
    

提交回复
热议问题