如何从 API 获取值?

PYJTER

我为这篇文章道歉,因为它对某些人来说可能看起来很平庸。但我想了解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;
    }
}

预先感谢您的帮助。

苦瓜

为了正确反序列化 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);
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章