AAP AAP - 3 months ago 27
JSON Question

Json Deserialize a webclient response C#

I am new in C# and I know there are hundreds of examples on the google for Json deserialization. I tried many but could not understand how C# works for deserialization.
`

using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "text/json");
result = client.UploadString(url, "POST", json);
}


`
result looks like this:

{"Products":[{"ProductId":259959,"StockCount":83},{"ProductId":420124,"StockCount":158}]}


First I created a class:

public class ProductDetails
{
public string ProductId { get; set; }
public string StockCount { get; set; }
}


Then I tried to deserialize using this statement but couldn't understand.

var jsonresult = JsonConvert.DeserializeObject<ProductDetails>(result);
Debug.WriteLine(jsonresult.ProductId);


The above worked fine in visual basic with the following code but how to do this similar in C#

Dim Json As Object
Set Json = JsonConverter.ParseJson(xmlHttp.responseText)

For Each Product In Json("Products")
Debug.Print = Product("ProductId")
Debug.Print = Product("StockCount")
Next Product

BWA BWA
Answer

You should use:

public class Product
{
    public int ProductId { get; set; }
    public int StockCount { get; set; }
}

public class RootObject
{
    public List<Product> Products { get; set; }
}

var jsonresult = JsonConvert.DeserializeObject<RootObject>(result);

Because your JSON contains list of products, in jsonresult you have list of Product.

If you want get Product you can use eg. foreach

foreach(Product p in jsonresult.Products)
{
    int id = p.ProductId;
}