首页 > 解决方案 > 使用 LINQ 提取 JSON 属性

问题描述

我有一个 json 对象,如下所示:

{
    "search-results": {
        "results-count": "2"
        "entry": [
            {
                "id": "0",
                "count": "10",
            },
            {
                "id": "1",
                "count": "22",
            }
        ]
    }
}

我想得到counts 的总和;32在这个例子中。我正在考虑使用 LINQ 执行此操作,但任何更“可读”的替代方案将不胜感激。

标签: c#jsonlinq.net-core

解决方案


试试这个:

var json = @"{
        'search-results': {
                    'results-count': '2',
                    'entry': [
                    {
                        'id': 0,
                        'count': 10,
                    },
                    {
                        'id': 1,
                        'count': 22,
                    }
            ]
        }
    }";


JObject searchResult = JObject.Parse(json);
int sum = (from entry in searchResult["search-results"]["entry"]
            select (int)entry["count"]).Sum();

推荐阅读