Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newtonsoft json is not deserializing when the name of the class is the root element

Newtonsoft json DeserializeObject is not parsing the json message when the name of the class is the root element.

var json = "  {\r\n \"amount\": {\r\n    \"currency\": \"EUR\",\r\n    \"value\": 99792\r\n  }\r\n}";
var amount = JsonConvert.DeserializeObject<Amount>(json)

and the class

class Amount 
{
    [JsonProperty("value")]
    public decimal? Value { get; set; }

    [JsonProperty("currency")]
    public string Currency { get; set; }
}

In that case the Amount properties are null. The problem is that the amount is nested in a more complex json and I found out that it is always returned empty because it starts with the "amount". Of course I tried some annotations in the Amount class like [DataContract] and [JsonObject] but still it is empty In case of:

 var json = "{\r\n    \"currency\": \"EUR\",\r\n    \"value\": 99792\r\n }";

Then is parsed properly. The question is how can I deseriale the json in the first case?

like image 968
Alexandros Mor Avatar asked Oct 24 '25 15:10

Alexandros Mor


2 Answers

You could create a wrapping class Root, which has a single element called Amount. For example,

public class Root
{
    [JsonProperty("amount")]
    public Amount Amount { get; set; }
}

You would now need to deserialize to an instance of Root. For example,

var amount = JsonConvert.DeserializeObject<Root>(json);

Alternatively, if you do not want to declare another class, you could also use

var innerJson = JObject.Parse(json)["amount"].ToString();
var amount = JsonConvert.DeserializeObject<Amount>(innerJson);
like image 107
Anu Viswan Avatar answered Oct 27 '25 00:10

Anu Viswan


You should model your classes like this:

public class Amount
{
    [JsonProperty("value")]
    public decimal? Value { get; set; }

    [JsonProperty("currency")]
    public string Currency { get; set; }
}

public class RootObject
{
    [JsonProperty("amount")]
    public Amount Amount { get; set; }
}

Then deserialize RootObject:

var amount = JsonConvert.DeserializeObject<RootObject>(json);

Note: You can paste your JSON into json2csharp.com, which models your JSON into C# classes for you.

like image 23
RoadRunner Avatar answered Oct 27 '25 00:10

RoadRunner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!