JsonPath with Newtonsoft.JSON

北慕城南 提交于 2019-12-14 03:47:48

问题


I tried for nearly an hour different approaches, but I don't get it ;(

my JSON object is this:

"typeOfHair": {
    "value": [
        {
            "code": "Dry Hair",
            "values": [
                {
                    "value": "DryHair",
                    "language": "en"
                },
                {
                    "value": "TrockenesHaar",
                    "language": "de"
                }
            ]
        },
        {
            "code": "Any Type of Hair",
            "values": [
                {
                    "value": "AnyTypeOfHair",
                    "language": "en"
                },
                {
                    "value": "JedenHaartyp",
                    "language": "de"
                }
            ]
        }
    ]
}

And my task is to get with Newtonsoft.JSON all values where the language is "de". My current approach is:

JsonObject.SelectTokens("typeOfHair.value.values[?(@.language == 'de')].value").ToList()

Can someone help me with this?

Kind regards


回答1:


You're very close. You need to account for the outer value array typeOfHair.value[] by using the JsonPATH wildcard operator [*]:

var values = JsonObject.SelectTokens("typeOfHair.value[*].values[?(@.language == 'de')].value")
    // Convert from JValue to string
    .Select(v => (string)v)
    // Save in a list
    .ToList();

And, the result is:

["TrockenesHaar","JedenHaartyp"]

Sample fiddle.




回答2:


I know the OP specified JSONPath explicitly but for the sake of completeness below is how to achieve the same with LINQ to JSON:

var values = jObject["typeOfHair"]["value"]
    .SelectMany(v => v["values"])
    .Where(v => (string)v["language"] == "de")
    .Select(v => (string)v["value"])
    .ToList();

Demo: https://dotnetfiddle.net/1S4sT4



来源:https://stackoverflow.com/questions/43458453/jsonpath-with-newtonsoft-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!