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

4

11

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

Fourthclass answered 16/8, 2017 at 13:57 Comment(0)
H
27

How about this one?

var str = "YOUR_JSON_HERE";
var obj = JsonConvert.DeserializeObject<dynamic>(str);
OrderStats info = ((JArray)obj.A)[0].ToObject<OrderStats>();
Hazardous answered 16/8, 2017 at 14:14 Comment(7)
Please pay attention that there is missing comma at the end of "M": "Receive"Hazardous
I can not change the class structureFourthclass
Don't you have a compilation error: 'OrderStatus': member names cannot be the same as their enclosing type?Hazardous
I am sorry for typo again, class name is OrderStatsFourthclass
I have fixed answerHazardous
Let us continue this discussion in chat.Hazardous
Solution if you don't have an array: ((JObject)Tags).ToObject<OrderStats>();Wastage
F
7

I found a solution a bit trivial like this,

dynamic obj = JsonConvert.DeserializeObject<dynamic>(message);
OrderStats info = JsonConvert.DeserializeObject<OrderStats>(JsonConvert.SerializeObject(obj.A[0]));
Fourthclass answered 16/8, 2017 at 14:26 Comment(1)
Because your error come from Cannot convert type 'Newtonsoft.Json.Linq.JObject' to Complex Type but your post is Conver from JSON string to Complex Type. So that @viktor's solution is correct for string convert, and your solution here is correct for Linq.JObject convert.Gauthier
B
0

i`m reviewing this solutions, but i think it's not necessary to use dynamic key,

i did this and it's work for me:

OrderStats info = JsonConvert.DeserializeObject(str)

It's simplified that other lines that you mention, but thanks for the advice, it was

correct for me

Bauhaus answered 30/9, 2022 at 6:24 Comment(0)
Q
0
string jsonString = "{\"name\": \"John Doe\", \"age\": 30, \"email\": \"[email protected]\"}";

// Parse the JSON string into a JObject
JObject jsonObject = JObject.Parse(jsonString);

// Convert the JObject into a complex type object
var person = jsonObject.ToObject<Person>();
Quartet answered 2/6, 2023 at 9:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.