How can I generate all possible LINQ strings of a json object for Json.net?

后端 未结 1 1872
攒了一身酷
攒了一身酷 2021-01-20 16:34

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:

1条回答
  •  囚心锁ツ
    2021-01-20 17:03

    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());
    

    0 讨论(0)
提交回复
热议问题