简体   繁体   中英

Find path/namespace of JToken in a Newtonsoft JObject

I have the following code example (C# using Newtonsoft Json.NET) that serializes a Json string into a JObject:

var obj = JObject.Parse("{\"F01\" : \"f01\", " +
                    "\"F02\" : \"f02\", " +
                    "\"L01\" : [" +
                        "{" +
                            "\"L01F01\" : \"l01f01\", " +
                            "\"L01F02\" : \"l01f02\"" +
                        "}, " +
                        "{" +
                            "\"L01F01\" : \"l01f01\", " +
                            "\"L01F02\" : \"l01f02\"" +
                        "}, " +
                        "{" +
                            "\"L01F03\" : \"l01f03\" " +
                        "}, " +
                        "{" +
                            "\"L01F03\" : \"l01f03\", " +
                            "\"L01L02\" : [" +
                                "{" +
                                    "\"L01L02F01\" : \"l01l02f01\"" +
                                "}" +
                            "]" +
                        "}" +
                    "]" +
                    "}");

Notice that the JSON has a dynamic structure where not all items in arrays has same names and attributes.

And I make the following JTokens:

var test01 = obj["F01"];
var test02 = obj["L01"][0]["L01F01"];
var test03 = obj["L01"][3]["L01L02"][0]["L01L02F01"];

I would like to know if somebody know any way to obtain the "path" of the test variables in this a way similar to:

GetPathOf(test01) => "F01"
GetPathOf(test02) => "L01[0].L01F01"
GetPathOf(test03) => "L01[3].L01L02[0].L01L02F01"

Thanks!

A Path property was added to JToken in release 5.0.1 (April 7, 2013) which does exactly what you describe.

So in your example you could simply write:

string path03 = test03.Path;

The path03 variable would then contain L01[3].L01L02[0].L01L02F01 .

Fiddle: https://dotnetfiddle.net/5Dhc4i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM