【问题标题】:How to get values from API?如何从 API 中获取值?
【发布时间】:2019-02-07 17:46:01
【问题描述】:

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

提前感谢您的帮助。

【问题讨论】:

  • 在网络上搜索“C# parse JSON”或“C# parse XML”并展示解决问题的尝试。
  • 我已将代码添加到原帖中,以供将来参考,请了解如何询问Minimal, Complete and Verifiable example。最好的学习方法是查看使用 WebClient 或 HttpClient` 调用 Web API 的示例,然后查看反序列化示例以将 JSON 字符串从字符串转换为对象表示。

标签: c# .net asp.net-web-api


【解决方案1】:

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

然后使用like:

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);
  }
}

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 2019-02-28
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多