Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialising a flat JSON object into a complex object using JSON.NET

Tags:

json

c#

json.net

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.

like image 247
Vistari Avatar asked Oct 20 '25 22:10

Vistari


1 Answers

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"]
                                               }  
                 };
like image 52
Tinwor Avatar answered Oct 22 '25 13:10

Tinwor