ibubi ibubi - 1 year ago 67
C# Question

Cannot convert type 'Newtonsoft.Json.Linq.JObject' to Complex Type

I have json as follows,

{
"H": "Macellum",
"M": "Receive",
"A": [
{
"CustomerId": "172600",
"OrderId": "69931",
"OrderStatus": "E0",
"Buy": "A"
}
]
}


and complex type

public class OrderStats
{
public string CustomerId { get; set; }
public string OrderId { get; set; }
public string OrderStatus { get; set; }
public string Buy { get; set; }
}


I am trying a casting as follows,

dynamic obj = JsonConvert.DeserializeObject<dynamic>(message);
OrderStats info = (OrderStats)obj.A[0]; //exception
OrderStats info = obj.A[0] as OrderStats; //info is null


But error as follows


Cannot convert type 'Newtonsoft.Json.Linq.JObject' to OrderStatus

Answer Source

How about this one?

var str = "YOUR_JSON_HERE";
var obj = JsonConvert.DeserializeObject<dynamic>(str);
OrderStats info = ((JArray)obj.A)[0].ToObject<OrderStats>();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download