c# - 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; }
}
解决方案
好的,这就是你的处理方式。我向您展示了一个示例,该示例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;
}
希望这可以帮助你。
编辑:
根据您的代码,您需要API
在Button
点击时调用:
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
在代码中放置块以进行错误处理。
推荐阅读
- opencv - OpenCV cv::Mat to System::Drawing::Bitmap throw System.ArgumentException (OpenCV C++/CLI, x64)
- python - Python 在文件中搜索字符串时提高性能
- android - Android AR 场景形式。移动 3D 模型随着相机移动。3D 模型应与底部对齐
- php - 使用 PHP Curl 检查 SSL 的到期日期
- java - 包含使用 AndroidX 的工具栏会使我的应用程序崩溃
- java - Java Scanner 在这种情况下如何工作?
- cuda - 如何获得 CUDA 中当前计算能力的最大共享内存量?
- spring-integration - Sftp 适配器文件大小限制
- java - Java Cassandra驱动从3迁移到4
- c - 二分搜索 2 数组错误