我不知道如何描述这一点,但我会尽我所能。我有一个 C# 应用程序,它采用我的 Web 应用程序的 API 并将它的 JSON 响应用作应用程序的数据。当用户单击按钮时,它会从 url 中提取响应并对其进行解析,以便可以使用它:
var client = new WebClient();
client.Headers.Add("User-Agent", "Nobody");
var response = client.DownloadString(new Uri("http://localhost:45035/api/products/1"));
var responsestring = response.ToString();
JObject o = JObject.Parse(responsestring);
Int32 Id = (int)o["Id"];
string Name = (string)o["Name"];
string Category = (string)o["Category"];
float Price = (float)o["Price"];
string Website = (string)o["Website"];
label1.Text = Name;
label2.Text = "$" + Price.ToString();
label3.Text = "Category: " + Category;
label4.Text = Id.ToString();
这很好用。问题是,当我有数千种产品时,这个应用程序将有上千个代码块,就像这样,只更改了 DownloadString Uri。我想把它变成一个类,这样我就可以插入适当的 Uri(例如http://example.com:45035/api/products/1或http://example.com:45035/api/products/2等)并从中获取名称、类别、ID 等,这样我的代码会更干净,但我不知道该怎么做。
我试过类似的东西:
public static object responseinfo(string url)
{
var client = new WebClient();
client.Headers.Add("User-Agent", "Nobody");
var response = client.DownloadString(new Uri(url));
var responsestring = response.ToString();
JObject o = JObject.Parse(responsestring);
Int32 Id = (int)o["Id"];
string Name = (string)o["Name"];
string Category = (string)o["Category"];
float Price = (float)o["Price"];
string Website = (string)o["Website"];
}
这允许我调用: jsonfind("http://localhost:45035/api/products/1") 但我不知道如何取出字符串,所以我可以像以前一样在文本框中使用它们。
我希望这种制作自始至终。这是我的第一个问题,所以如果我需要更改一些或很多,请告诉我。
作为记录,我正在使用 Json.NET 处理 JSON 响应。
谢谢,
米切尔