I'm not sure how to describe this, but I'm going to do the best I can. I have a C# app that takes the API of my web app and uses it's JSON response as the data of the app. When a user clicks a button then it pulls the response from the url and parses it so it can be used:
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();
That works great. The problem is, when I have thousands of products, this app will have a thousand of code blocks just like this with only the DownloadString Uri changed. I wanted to turn this into one class so I can plug in the appropriate Uri (eg. http://example.com:45035/api/products/1 or http://example.com:45035/api/products/2, etc.) and from that get the Name, Category, Id, etc. from it so my code would be cleaner, but I can not figure out how to do that.
I tried something like:
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"];
}
That allows me to call: jsonfind("http://localhost:45035/api/products/1") but I don't know how to get the strings out so I can use them in the text box like I did before.
I hope that this kind of makes since. It's my first question so if I need to change some, or a lot please tell me.
For the record I am using Json.NET do deal with the JSON responses.
Thanks,
Mitchell