[ { "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());
Newtonsoft. Json uses reflection to get constructor parameters and then tries to find closest match by name of these constructor parameters to object's properties. It also checks type of property and parameters to match. If there is no match found, then default value will be passed to this parameterized constructor.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array.
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
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;
If you only care about checking status
you can use the dynamic
type of .NET (https://msdn.microsoft.com/en-us/library/dd264741.aspx)
dynamic deserialized = JObject.Parse(responseString); int status1 = deserialized[0].status; int status2 = deserialized[1].status; // // do whatever
This way you don't even need the Example
class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With