简体   繁体   中英

Need to retrieve data from a certain API in Json (C#)

I need to retrieve the name of every product from an API to a listbox in C# (Visual Studio) and I've managed to login sucessfully into the API. I was able to retrieve the data of each product serialized but when I try to deserialize it the result for each product comes like this: 'app1.Form1+Data'. How can I retrieve the name of each product correctly?

Code:

public class Data
{
        public int id { get; set; }
        public string name { get; set; }
}


private void Form1_Load(object sender, EventArgs e)

{

for (int i = 1; i <= 20; i++)
{
    string url = reqlbl.Text;
    WebClient c = new WebClient();
    String userName = "user";
    String passWord = "pass";
    string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
    c.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;
    var json = c.DownloadString(url + i.ToString());
    Data result = JsonConvert.DeserializeObject<Data>(json);
    listBox1.Items.Add(result);

    }

}

Note: The variable 'i' represents a product. There are 20 products in total.

Here's an API example of product 1:

{"1":{"id":1,"name":"Product1"}}

The json is basically a dictionary, ie assuming it can return more than 1 product or something similar, or maybe its just lazily built api, who knows

Exmaple

var str = "{\"1\":{\"id\":1,\"name\":\"Product1\"}}";
var dataDict = JsonConvert.DeserializeObject<Dictionary<string, Data>>(str);

foreach (var data in dataDict.Values)
    Console.WriteLine(data.id + ", " + data.name);

Output

1, Product1

Demo here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM