我为这篇文章表示歉意,因为它对某些人来说似乎太平庸了。但不幸的是,我想了解 GET API 的操作,但是我仍然找不到可访问的教程。作为从示例中学习的最佳方法,有人可以向我展示如何以最简单的方式从名称标签中获取值吗?最多可以是textBox。
在xml中:
https://bdl.stat.gov.pl/api/v1/subjects?lang=pl&format=xml
在json中
https://bdl.stat.gov.pl/api/v1/subjects?lang=pl&format=json
代码
public class Result
{
public string id { get; set; }
public string name { get; set; }
public bool hasVariables { get; set; }
public List<string> children { get; set; }
public string levels { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
using (WebClient wc = new WebClient())
{
wc.Encoding = System.Text.Encoding.UTF8;
var json = wc.DownloadString("https://bdl.stat.gov.pl/api/v1/subjects?lang=pl&format=json");
Result result = JsonConvert.DeserializeObject<Result>(json);
richTextBox1.Text = result.name;
}
}
预先感谢您的帮助。
答案 0 :(得分:2)
为了使您的JSON字符串正确反序列化,您缺少各种类。试试:
public class Results
{
public string id { get; set; }
public string name { get; set; }
public bool hasVariables { get; set; }
public List<string> children { get; set; }
public string levels { get; set; }
}
public class Links
{
public string first { get; set; }
public string self { get; set; }
public string next { get; set; }
public string last { get; set; }
}
public class JsonObject
{
public int totalRecords { get; set; }
public int page { get; set; }
public int pageSize { get; set; }
public Links links { get; set; }
public List<Results> results { get; set; }
}
然后使用:
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("https://bdl.stat.gov.pl/api/v1/subjects?lang=pl&format=json");
JsonObject result = JsonConvert.DeserializeObject<JsonObject>(json);
foreach (var res in result.results)
{
MessageBox.Show(res.name);
}
}