.Net,如何遍历JSon对象?

时间:2017-09-06 19:00:36

标签: c# asp.net json

我正在尝试迭代以下每个键/值:

"sprites": {
    "back_female": null,
    "back_shiny_female": null,
    "back_default": "some url"
    "front_female": null,
    "front_shiny_female": null,
    "front_shiny": "some url"
},

在我的ApiCaller.cs中:

    JObject PokeObject = JsonConvert.DeserializeObject<JObject>(StringResponse);
    JObject SpriteList = PokeObject["sprites"].Value<JObject>();
    List<string> Sprites = new List<string>();

     foreach(KeyValuePair<string, string> entry in SpriteList) {
                    if(entry.Value != null){
                        Sprites.Add(entry.Value);
                    }
                }

我得到了:

 Cannot convert type 'System.Collections.Generic.KeyValuePair<string, Newtonsoft.Json.Linq.JToken>' to 'System.Collections.Generic.KeyValuePair<string, string>

有人可以帮我解决这个问题吗? 谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用ToObject<T>方法:

var Sprites = PokeObject["sprites"]
    .ToObject<Dictionary<string, string>>()
    .Select(x => x.Value)
    .Where(x => x != null)
    .ToList();