我正在尝试了解如何调用API(Pokeapi)并将响应中收到的数据解析为C#中外部库(PokeApi.NET)中的对象。
我在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"},...
答案 0 :(得分:1)
这应该是你的班级结构。
import javax.swing.JOptionPane;
import java.util.Arrays;
public class RainfallApp {
public static void main(String[] args) {
int[][] rain = new int[4][7];
int[] average = new int[4];
Rainfall r = new Rainfall();
r.setRain(rain);
r.compute();
average = r.getAverage();
JOptionPane.showMessageDialog(null, "The average for each week is: "+Arrays.toString(average));
}
这必须是有效的json。
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; }
}
答案 1 :(得分:1)
使用Newtonsoft软件包,您可以像此示例一样反序列化您的JSON。还可以使用json2sharp工具从JSON生成C#
类。
如果在Visual Studio中有Web Essentials
,则可以随时使用
修改&gt;粘贴特殊&gt;将JSON粘贴为类。
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);