我不知道如何描述这一点,但我会尽力而为。我有一个 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 响应。
谢谢
米切尔
最佳答案
解决您的问题最直接的方法是使用 out
parameters :
public void GetTwoNumers(out int num1, out int num2) {
num1 = 4;
num2 = 2;
}
更好的解决方案是将 WebClient
代码提取到一个返回 JObject
的单独函数中:
public static JObject WebRequest(string url) {
var client = new WebClient();
client.Headers.Add("User-Agent", "Nobody");
var response = client.DownloadString(new Uri(url));
var responsestring = response.ToString();
return JObject.Parse(responsestring);
}
然后,在许多其他 API 调用函数中使用该函数,每个函数都返回自己的类以及相关字段:
public class Item {
public int Id { get; private set; }
public string Name { get; private set; }
public string Category { get; private set; }
public float Price { get; private set; }
public string Website { get; private set; }
private Item() {
}
public static Item GetFromUrl(string url) {
var o = WebRequest(url);
return new Item() {
Id = (int)o["Id"],
Name = (string)o["Name"],
Category = (string)o["Category"],
Price = (float)o["Price"],
Website = (string)o["Website"],
};
}
}
然后调用此代码:
private void button1_Click(object sender, EventArgs e) {
string url = "...";
var item = Item.GetFromUrl(url);
MessageBox.Show("You found item #" + item.Id + " named " + item.Name);
txtBoxName.Text = item.Name;
txtBoxCat.Text = item.Category;
}
注意,我在这里使用了静态工厂方法GetFromUrl
,并将构造函数设置为私有(private)。所以你只能通过该静态方法获取实例。并非完全必要,但在我看来,这是一个很好的技术。
关于具有多个返回 string 和 int 的 C# 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11662475/