AAP AAP - 1 year ago 167
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:


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);

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

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download