I am retrieving some JSON from an external API that I have no control over and need to deserialise that into an object where some of the fields are nested into a property of the main object so a straight deserialise won't work.
The closest question I've found to my issue is:
Json .Net serialize flat object into a complex object (change objects structure on serialization/deserialization)
I couldn't really apply this to my problem though as i'm fairly new to using JSON.NET and still trying to understand how it works.
A small sample to demonstrate of the json back from the API:
{
FirstName: "John",
LastName: "Smith",
PassportNo: "xxxxx",
NiNo: "xxxxx",
}
The class(es) I want to deserialise into:
internal sealed class Person
{
[JsonProperty(PropertyName = "FirstName")]
public string FirstName { get; set; }
[JsonProperty(PropertyName = "LastName")]
public string LastName { get; set; }
public PrivateData PrivateData { get; set; }
}
internal sealed class PrivateData
{
[JsonProperty(PropertyName = "PassportNo")]
public string PassportNo { get; set; }
[JsonProperty(PropertyName = "NiNo")]
public string NationalInsuranceNumber { get; set; }
}
I wasn't sure how to go about implementing a custom contract resolver / JSON converter to attain the required results so any guidance would be appreciated.
You cannot use the default JsonConvert
class of JSON.Net
because it's not able to convert a flat json structure in a complex class. If I were in you I'll parse the json as a Dictionary<string, string>
and then create your person class.
Something like this:
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
var person = new Person {
FirstName = values["FirstName"] ,
LastName = values["LastName "],
PrivateData = new PrivateData {
PassportNo = values["PassportNo"],
NationalInsuranceNumber = values["NiNo"]
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With