Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 477
ibubi Avatar asked Aug 16 '17 13:08

ibubi


1 Answers

How about this one?

var str = "YOUR_JSON_HERE";
var obj = JsonConvert.DeserializeObject<dynamic>(str);
OrderStats info = ((JArray)obj.A)[0].ToObject<OrderStats>();
like image 155
Viktor Oleksyshyn Avatar answered Sep 18 '22 09:09

Viktor Oleksyshyn