Deserialize a JSON string into a C# object and set custom values into a property of that object

This week I had to deserialize a JSON string into a collection of C# objects. The class of these objects contained not only the properties that map directly to the JSON properties but also an extra property which I wanted to fill with values based on the values of other properties of the object.

Let us consider the following simple POCO class and its container, which is a simple array of Students:

public class Student
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string FullName { get; set; }

    public int AgeInYears { get; set; }
}

public class StudentsList
{
    public Student[] Students { get; set; }
}

The JSON we receive contains a list of students with their first name, their last name and their age. However, we want to concatenate the first and last names and store it in the FullName property. Now we want to do that while we deserialize the JSON string and not afterwards.

The solution is to define a constructor in the POCO class which takes as parameters the properties that we want to use to fill our custom property with. The names of the parameters should be the same as in the JSON string, in that case in camelCase format:

public class Student
{
    [JsonConstructor]
    public Student(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;

        FullName = FirstName + " " + LastName;
    }

    // properties...
}

Inside the constructor we have to manually do the mapping of the parameters to their equivalent C# properties. The remaining properties are going to be mapped automatically. Pay attention to the JsonConstructor attribute I added on top of the constructor.

Lastly we do our custom logic and write the first and last names inside the FullName property.

For deserializing the JSON string I use the following code from the Newtonsoft.Json Nuget package:

    var students = JsonConvert.DeserializeObject<StudentList>(jsonString);
comments powered by Disqus