JSON获取属性值列表

时间:2017-06-08 21:26:36

标签: c# json linq json.net

我有以下JSON,我想要一个带有值

的ID列表

例如在LINQ中,例如: result.Select(x => x.id)

我试过了:

 var inner = outer["pictures"].Value<JArray>().ToList();

我有一个列表,但有所有属性但我不能只选择ID,因为它是一个匿名列表。

    outer
{{
  "id": "669654603",
  "pictures": [
    {
      "id": "659745-MLA25600661898_052017",
      "url": "http://mla-s2-p.mlstatic.com/659745-MLA25600661898_052017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/659745-MLA25600661898_052017-O.jpg",
      "size": "500x365",
      "max_size": "625x457",
      "quality": ""
    },
    {
      "id": "908422-MLA25658267858_062017",
      "url": "http://mla-s2-p.mlstatic.com/908422-MLA25658267858_062017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/908422-MLA25658267858_062017-O.jpg",
      "size": "47x47",
      "max_size": "47x47",
      "quality": ""
    },
    {
      "id": "794138-MLA25658267889_062017",
      "url": "http://mla-s2-p.mlstatic.com/794138-MLA25658267889_062017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/794138-MLA25658267889_062017-O.jpg",
      "size": "40x40",
      "max_size": "40x40",
      "quality": ""
    }
  ]


}}

2 个答案:

答案 0 :(得分:1)

使用Newtonsoft JSON时,您可以这样做:

var values = JObject.Parse(jsonString)["pictures"].Select(p => p["id"].Value<string>()).ToList();

答案 1 :(得分:0)

为了有效,你的json不应该包含双花括号:

{
  "id": "669654603",
  "pictures": [ ... ]
}

您无需额外的课程即可解析它:

var ids = JObject.Parse(json)["pictures"].Select(p => (string)p["id"]);

输出:

[
  "659745-MLA25600661898_052017",
  "908422-MLA25658267858_062017",
  "794138-MLA25658267889_062017"
]

或者您可以创建几个类来保存您的json数据:

public class Container
{
    public List<Picture> Pictures { get; set; }
}

public class Picture
{
    public string Id { get; set; }
    // you can add other properties here
}

使用强类型解析:

var ids = JsonConvert.DeserializeObject<Container>(json).Pictures.Select(p => p.Id);