In json.net we can using linq to json based on this tutorial.
I want to know is there any way to generate a string query or not? Consider this json example:
You can use SelectTokens("..*") to recursively descent the JSON token hierarchy, where ".."
is the JSONPath recursive descent operator and "*"
is a wildcard matching anything. Then you can use JToken.Path as your dictionary key:
var dic = linq.SelectTokens("..*")
.ToDictionary(t => t.Path, t => t.ToString());
Note this includes the root token. If you want to skip it, do:
var dic = linq.SelectTokens("..*")
.Where(t => t != linq)
.ToDictionary(t => t.Path, t => t.ToString());
You could also use JContainer.DescendantsAndSelf() or JContainer.Descendants() to do the recursive descent, filtering out all JProperty
nodes for the same result:
var dic = linq.Descendants()
.Where(t => t.Type != JTokenType.Property)
.ToDictionary(t => t.Path, t => t.ToString());