AAP
AAP

Reputation: 169

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

Upvotes: 3

Views: 13156

Answers (3)

jambonick
jambonick

Reputation: 716

Your C# code cannot work because your json string contains values for 2 Product objects. As a result your var jsonresult variable will contain an array of Product objects, not one. It is obvious in your VB code as you need to loop the Json variable in order to acquire each Product object. Still your C# code would work if you string contained values for only one object like this:

{"ProductId" = 420124,"StockCount" = 158}

as you can see here http://www.newtonsoft.com/json/help/html/SerializingJSON.htm

Also you can try json parsing with JObject class, check this out: http://www.newtonsoft.com/json/help/html/t_newtonsoft_json_linq_jobject.htm

Upvotes: 0

BWA
BWA

Reputation: 5764

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

Upvotes: 3

Anton Gogolev
Anton Gogolev

Reputation: 115691

Your JSON reads "an object that has a property named Products which contains an array of objects with properties ProductId and StockCount". Hence,

public class Inventory
{
    public ProductDetails[] Products { get; set; }
}

var inventory = JsonConvert.DeserializeObject<Inventory>(result);

Upvotes: 2

Related Questions