0

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"}}

11
  • 1
    Shoult it be {"Data":{"id":1,"name":"Product1"}}? Commented Apr 11, 2018 at 8:54
  • I don't think so, the number 1 is representing the object/product number. Commented Apr 11, 2018 at 8:56
  • 1
    That json doesn't make sense to me. Commented Apr 11, 2018 at 9:07
  • You probably need to add another class Product that has an int id and Data item as members, and then Deserialize to product instead of Data Commented Apr 11, 2018 at 9:07
  • @Achilles While I agree with the structure, a key of name "1" seems pretty odd. Commented Apr 11, 2018 at 9:08

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.