如何使用 linq 从这个 json 字符串中提取特定值

How to extract specific value from this json string using linq

谁能帮我从以下 json 字符串中提取 [downloads][csv][href] 的具体值?

{
"@context": "https://cdn.ons.gov.uk/assets/json-ld/context.json",
"alerts": [],
"collection_id": "cmdr",
"dimensions": [
    various dimensions here
],
"downloads": {
    "csv": {
        "href": "https://download.beta.ons.gov.uk/downloads/datasets/regional-gdp-by-year/editions/time-series/versions/4.csv",
        "size": "568021"
    },
    "csvw": {
        "href": "ref",
        "size": "1903"
    },
    "xls": {
        "href": "ref",
        "size": "80768"
    }
},
"edition": "time-series",
"id": "5c",
"links": {
    "dataset": {
        "href": "ref",
        "id": "regional-gdp-by-year"
    },
    "edition": {
        "href": "ref",
        "id": "time-series"
    },
    "self": {
        "href": "ref"
    }
},
"release_date": "2021",
"state": "published",
"usage_notes": [],
"version": 4

}

我正在使用的当前代码returns没有:

        var labels = JObject.Parse(observationsJson)["downloads"];
        var results = labels.Select(data => new
        {
            label = (string)data["href"]
        });
        foreach (var item in results)
        {
            csvDownloadAddress = item.label;
        }

如果有其他方法而不是使用 linq,那么我愿意接受建议。 抱歉,如果这是一个愚蠢的任务,我在 linq 和 json 方面的经验非常有限。 谢谢你的帮助。

您有 JSON Path,可用于 select specific 字符串中的 JSON 元素。 请参阅 Newtonsoft example, or you can use this JsonPath Nuget 包。

JsonPath Nuget 可以像下面这样使用,

    var input = "$.downloads.csv.href";
    var path = JsonPath.Parse(input);
    var hrefVal = path.Evaluate(jsonStr);