解析来自Pokeapi的JSON



我试图理解如何调用API (Pokeapi)和解析响应中接收到的数据在一个外部库(Pokeapi . net)在c#中的对象。

我在c#代码中收到响应,但我很难将响应解析为对象。

我相信问题是与最后一行代码,但我不确定它应该是什么?

c#代码:

private static string URL = "http://pokeapi.co/api/v2/pokemon/";
static async void GetPokemonAsync()
{
    string page = URL;
    using (HttpClient client = new HttpClient())
    using (HttpResponseMessage response = await client.GetAsync(page))
    using (HttpContent content = response.Content)
    {
        string result = await content.ReadAsStringAsync();
        if (result != null && result.Length >= 50)
        {
            Console.WriteLine(result.Substring(0,200));
            PokeAPI.Pokemon a = JsonConvert.DeserializeObject<PokeAPI.Pokemon>(result);
        }
    }
}

结果示例:

{"count":811,"previous":null,"results":[{"url":"http://pokeapi.co/api/v2/pokemon/1/","name":"bulbasaur"},{"url":"http://pokeapi.co/api/v2/pokemon/2/","name":"ivysaur"},{"url":"http://pokeapi.co/api/v2/pokemon/3/","name":"venusaur"},{"url":"http://pokeapi.co/api/v2/pokemon/4/","name":"charmander"},{"url":"http://pokeapi.co/api/v2/pokemon/5/","name":"charmeleon"},{"url":"http://pokeapi.co/api/v2/pokemon/6/","name":"charizard"},...

这应该是你的类结构。

public class Result
{
    public string url { get; set; }
    public string name { get; set; }
}
public class Pokemon
{
    public int count { get; set; }
    public object previous { get; set; }
    public List<Result> results { get; set; }
}

必须是有效的json。

{
"count": 811,
"previous": null,
"results": [{
    "url": "http://pokeapi.co/api/v2/pokemon/1/",
    "name": "bulbasaur"
}, {
    "url": "http://pokeapi.co/api/v2/pokemon/2/",
    "name": "ivysaur"
}, {
    "url": "http://pokeapi.co/api/v2/pokemon/3/",
    "name": "venusaur"
}, {
    "url": "http://pokeapi.co/api/v2/pokemon/4/",
    "name": "charmander"
}, {
    "url": "http://pokeapi.co/api/v2/pokemon/5/",
    "name": "charmeleon"
}, {
    "url": "http://pokeapi.co/api/v2/pokemon/6/",
    "name": "charizard"
}]
}

使用Newtonsoft包,您可以像这个示例一样反序列化JSON。也可以使用json2sharp工具从JSON生成C#类。

如果你在Visual Studio中有Web Essentials,你总是可以使用

Edit> Paste special>将JSON粘贴为class。

public class Result
{
    public string url { get; set; }
    public string name { get; set; }
}
public class RootObject
{
    public int count { get; set; }
    public object previous { get; set; }
    public List<Result> results { get; set; }
}
var  results = JsonConvert.DeserializeObject<RootObject>(json);

相关内容

  • 没有找到相关文章