How do I deserialize a JSON array using Newtonsoft.Json

Steven picture Steven · Dec 5, 2015 · Viewed 50.8k times · Source
[
   {
      "receiver_tax_id":"1002",
      "total":"6949,15",
      "receiver_company_name":"Das Company",
      "receiver_email":"[email protected]",
      "status":0
   },
   {
      "receiver_tax_id":"1001",
      "total":"39222,49",
      "receiver_company_name":"SAD company",
      "receiver_email":"[email protected]",
      "status":1
   }
]

Hi, this is my Json data, but I can't deserialize it. I want to check only "status" value. (first object "status" 0, second object "status" 1).

Example definition:

public class Example 
{
    [JsonProperty("receiver_tax_id")] 
    public string receiver_tax_id { get; set; }
    [JsonProperty("total")] 
    public string total { get; set; }
    [JsonProperty("receiver_company_name")] 
    public string receiver_company_name { get; set; }
    [JsonProperty("receiver_email")] 
    public string receiver_email { get; set; }
    [JsonProperty("status")] 
    public int status { get; set; } 
}

Deserialization code:

var des = (Example)JsonConvert.DeserializeObject(responseString, typeof(Example)); 
Console.WriteLine(des.status[0].ToString());

Answer

Maxim Goncharuk picture Maxim Goncharuk · Dec 5, 2015

Try this code:

public class Receiver 
{
   public string receiver_tax_id { get; set;}
   public string total { get; set;}
   public string receiver_company_name { get; set;}
   public int status { get; set;}
}

And deserialize looks like follows:

var result = JsonConvert.DeserializeObject<List<Receiver>>(responseString);
var status = result[0].status;