Using Newtonsoft JsonConvert to easily construct a derived class from a base instance

Okay, so this may not be the most efficient code – so you may not want to use this in a context where milli seconds matter. But say you have a model class (returned by another library or from an API) and you need to extend it by adding a single property to it. The simplest way to do this is to derive a new class, add the property to it and then to add a constructor that copy-constructs from base to derived. Bit of a hassle having to copy every single property though, although I’d imagine some of those new AI powered IDEs could auto-generate code for you. Even then, if the base class ever changes, you will need to update this constructor and if you forget to do that, there’s a risk of random buggy behavior. So, what’s the hack? Use JsonConvert to serialize the base object, then deserialize it to derived and then populate the new field or fields that’s been added to derived.

static void Main()
{
    ModelEx model = Foo(new Model
    {
        Id = 1000,
        Name = "Mary Miller",
        Description = "Senior Accountant"
    });
    model.Enabled = true;
}

private static ModelEx Foo(Model model)
{
    var json = JsonConvert.SerializeObject(model);
    return JsonConvert.DeserializeObject<ModelEx>(json);
}

class ModelEx : Model
{
    public bool Enabled { get; set; }
}

class Model
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

Leave a comment