在C#中迭代JSON对象

req*_*nce 44 c# json json.net c#-4.0

我在C#中使用JSON.NET来解析来自Klout API的响应.我的回答是这样的:

[
  {
    "id": "5241585099662481339",
    "displayName": "Music",
    "name": "music",
    "slug": "music",
    "imageUrl": "http://kcdn3.klout.com/static/images/music-1333561300502.png"
  },
  {
    "id": "6953585193220490118",
    "displayName": "Celebrities",
    "name": "celebrities",
    "slug": "celebrities",
    "imageUrl": "http://kcdn3.klout.com/static/images/topics/celebrities_b32741b6703151cc7bd85fba24c44c52.png"
  },
  {
    "id": "5757029936226020304",
    "displayName": "Entertainment",
    "name": "entertainment",
    "slug": "entertainment",
    "imageUrl": "http://kcdn3.klout.com/static/images/topics/Entertainment_7002e5d2316e85a2ff004fafa017ff44.png"
  },
  {
    "id": "3718",
    "displayName": "Saturday Night Live",
    "name": "saturday night live",
    "slug": "saturday-night-live",
    "imageUrl": "http://kcdn3.klout.com/static/images/icons/generic-topic.png"
  },
  {
    "id": "8113008320053776960",
    "displayName": "Hollywood",
    "name": "hollywood",
    "slug": "hollywood",
    "imageUrl": "http://kcdn3.klout.com/static/images/topics/hollywood_9eccd1f7f83f067cb9aa2b491cd461f3.png"
  }
]
Run Code Online (Sandbox Code Playgroud)

如您所见,它包含5个id标签.也许下次它会是6或1或其他一些数字.我想迭代JSON并获取每个id标记的值.在不知道会有多少循环的情况下,我无法运行循环.我怎么解决这个问题?

L.B*_*L.B 82

dynamic dynJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynJson)
{
    Console.WriteLine("{0} {1} {2} {3}\n", item.id, item.displayName, 
        item.slug, item.imageUrl);
}
Run Code Online (Sandbox Code Playgroud)

要么

var list = JsonConvert.DeserializeObject<List<MyItem>>(json);

public class MyItem
{
    public string id;
    public string displayName;
    public string name;
    public string slug;
    public string imageUrl;
}
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,'dynamic'关键字可以从框架4.0开始提供:( (2认同)

ret*_*ent 39

您可以使用它JsonTextReader来读取JSON并迭代令牌:

using (var reader = new JsonTextReader(new StringReader(jsonText)))
{
    while (reader.Read())
    {
        Console.WriteLine("{0} - {1} - {2}", 
                          reader.TokenType, reader.ValueType, reader.Value);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然这不是必需的,但这是唯一允许您在不事先知道结构的情况下迭代JObject的答案 (9认同)
  • 这是一个非常好的答案,它提供了对解析的JSON的完全控制的选项.非常有用,谢谢! (3认同)