Get path of JSON value using JSON.NET

后端 未结 4 845
北恋
北恋 2021-01-11 12:14

I am trying to find a path of a JSON value. Consider the following JSON:

{
    \"car\": {
        \"type\": [{
            \"sedan\": {
                \"mak         


        
4条回答
  •  心在旅途
    2021-01-11 13:14

    Update to the latest version of Json.NET. The Path property was added to JToken in version 5.0 release 1 (April 7, 2013).

    Here is a test program you can use to verify that it works:

    class Program
    {
        static void Main(string[] args)
        {
            string json = @"
            {
                ""car"": {
                    ""type"": [{
                        ""sedan"": {
                            ""make"": ""honda"",
                            ""model"": ""civics""
                        }
                    },
                    {
                        ""coupe"": {
                            ""make"": ""ford"",
                            ""model"": ""escort""
                        }
                    }]
                }
            }";
    
            JObject obj = JObject.Parse(json);
            JToken token = obj["car"]["type"][0]["sedan"]["make"];
            Console.WriteLine(token.Path + " -> " + token.ToString());
        }
    }
    

    Output:

    car.type[0].sedan.make -> honda
    

提交回复
热议问题