Home > Back-end >  Unable to deserialise result to model
Unable to deserialise result to model

Time:12-09

I have the following classes:

public class Countries
{
    public List<Country> countries { get; set; }
}

public class Country
    {
    public string countryName { get; set; }
    public string region { get; set; }
    public string code { get; set; }
}

Which is being read in via a HttpRequest:

enter image description here

But when I try to deserialise the result:

var Mycountries = JsonConvert.DeserializeObject<Countries>(body);

But the Mycountries variable is always null.

Obviously I'm missing something obvious and I wonder if someone could help me out please?

UPDATE

Trying a different approach produces the following:

enter image description here

CodePudding user response:

TL;DR use the JsonProperty attribute

Add it to your Countries class:

[JsonProperty("Data")]
public class Countries
{
    public List<Country> countries { get; set; }
}

Why?

When using the JsonConvert.DeserializeObject method to deserialize a JSON string, but the property names in the JSON string do not match the property names of the target object, you should use the JsonProperty attribute to specify the correct names.

I hope that helps!

CodePudding user response:

Looks like you have a serialized array inside a serialized object, which is why the quotation marks are escaped by 3 backslashes. So because it is serialized 2 times (for whatever reason), you have to deserialize it 2 times; kind of like this:

JObject jObject = (JObject) JsonConvert.DeserializeObject(body);
    
var Mycountries = new Countries();
Mycountries.contries = JsonConvert.DeserializeObject<List<Country>>(jObject.GetValue("Data").ToString());
  • Related