首页 > 解决方案 > C# JSON URL 获取数据

问题描述

我是使用 C# 的 System.Net 的新手我想要一种从这个网站 api 获取信息的方法:https ://fn-api.glitch.me/api/aes 从它的 json 到 C# 字符串

到目前为止我有这个

我不知道如何获取每个项目以及将网址放在哪里(我对此真的很陌生)。

我想要字符串中的网址:

public class Data
{
    public string build { get; set; }
    public string netCL { get; set; }
    public string manifestID { get; set; }
    public string aes { get; set; }
}

public class RootObject
{
    public Data data { get; set; }
}

标签: c#jsonparsinggetset

解决方案


好的,这就是你的处理方式。我向您展示了一个示例,该示例HttpClient首先从 API 读取内容,然后使用 package.json 对其进行反序列化Newtonsoft

HttpClient 类:

public class HttpClientFactory
{
  private string webServiceUrl = "https://fn-api.glitch.me/";

  public HttpClient CreateClient()
  {
    var client = new HttpClient();
    SetupClientDefaults(client);
    return client;
  }

  protected virtual void SetupClientDefaults(HttpClient client)
  {
    //This is global for all REST web service calls
    client.Timeout = TimeSpan.FromSeconds(60);
    client.BaseAddress = new Uri(webServiceUrl);
  }
}

你的模型类:

public class Data
{
  public string build { get; set; }
  public string netCL { get; set; }
  public string manifestID { get; set; }
  public string aes { get; set; }
}

public class RootObject
{
  public Data data { get; set; }
}

现在,你可以调用这个类并创建一个这样的实例HttpClient

public RootObject InvokeAPI()
{
  RootObject apiresponse = new RootObject();
  string result = string.Empty;
  HttpClientFactory clientFactory = new HttpClientFactory();
  var client = clientFactory.CreateClient();
  HttpResponseMessage response = client.GetAsync("api/aes").Result;
  if (response.IsSuccessStatusCode)
  {
    result = response.Content.ReadAsStringAsync().Result;
    apiresponse = JsonConvert.DeserializeObject<RootObject>(result);
  }
 return apiresponse;
}

希望这可以帮助你。

编辑:

根据您的代码,您需要APIButton点击时调用:

    private void metroButton2_Click_1(object sender, EventArgs e)
    {
        //You need to invoke the API method !!!!
        var apiresponse=InvokeAPI();
        metroTextBox1.Text = apiresponse.data.aes;
    }

确保try-catch在代码中放置块以进行错误处理。


推荐阅读