C#使用Newtonsoft.Json提取json对象数组

时间:2017-08-28 22:11:13

标签: c# json json.net

如何在List<String>中抓取所有令牌? 这是json字符串:

{
    "error": null,
    "jsonrpc": "2.0",
    "id": 0,
    "result": {
        "paginator": null,
        "cat_count": {},
        "last_post_date": 386623075949839,
        "post_list": [
            {
                "hc": false,
                "p2": 4,
                "token": "LnARJZCmt"
            },
            {
                "hc": false,
                "p2": 4,
                "token": "BuD2oIs3N"
            },
            {
                "p2": 4,
                "token": "89NaBsAha",
                "hc": false,
            }
        ],
        "error": 0
    }
}

我正在使用Newtonsoft.Json
这是我试过的:

    var obj = JObject.Parse(json);
    string next_search_val = (string)obj["result"]["last_post_date"];
    var tokens = obj["result"]["post_list"]["token"]; > Fix this line for me > I have error here

1 个答案:

答案 0 :(得分:3)

我会用

var tokens = JObject.Parse(json)
                .SelectTokens("$..token")
                .Select(x => (string)x)
                .ToList();

修改

没有JsonPath的同样的事情

var tokens = JObject.Parse(json)
                .Descendants()
                .OfType<JProperty>()
                .Where(x => x.Name == "token")
                .Select(x => x.Value)
                .ToList();

编辑2

您最近的尝试

var tokens = JObject.Parse(json)["result"]["post_list"]
                .Select(x => (string)x["token"])
                .ToList();