Click here to Skip to main content
16,021,285 members
Articles / Programming Languages / C#
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.85/5 (5 votes)
29 Sep 2023CPOL1 min read 10.6K   1   8
Minimal code to copy a base object into a derived instance

Introduction

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.

Using the code

C#
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; }
}

As a commenter pointed out, you don't need to use Newtonsoft for this. You can use the more native System.Text.Json classes, if you prefer. But if your codebase predominantly uses Newtonsoft, you can stay with that. 

C#
var json = JsonSerializer.Serialize(model);
return JsonSerializer.Deserialize<ModelEx>(json);

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Nish Nishant is a technology enthusiast from Columbus, Ohio. He has over 20 years of software industry experience in various roles including Chief Technology Officer, Senior Solution Architect, Lead Software Architect, Principal Software Engineer, and Engineering/Architecture Team Leader. Nish is a 14-time recipient of the Microsoft Visual C++ MVP Award.

Nish authored C++/CLI in Action for Manning Publications in 2005, and co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is experienced in technology leadership, solution architecture, software architecture, cloud development (AWS and Azure), REST services, software engineering best practices, CI/CD, mentoring, and directing all stages of software development.

Nish's Technology Blog : voidnish.wordpress.com

Comments and Discussions

 
QuestionWhy Newtonsoft? Pin
MSBassSinger2-Oct-23 5:48
professionalMSBassSinger2-Oct-23 5:48 
AnswerRe: Why Newtonsoft? Pin
Nish Nishant2-Oct-23 7:02
sitebuilderNish Nishant2-Oct-23 7:02 
GeneralRe: Why Newtonsoft? Pin
MSBassSinger2-Oct-23 7:10
professionalMSBassSinger2-Oct-23 7:10 
Quote:
I suppose you can use the more native lib if you prefer that.


It makes more sense to me to use the built-in .NET functionality instead of the older third-party library when both provide the same functionality.
GeneralRe: Why Newtonsoft? Pin
Nish Nishant2-Oct-23 7:11
sitebuilderNish Nishant2-Oct-23 7:11 
GeneralRe: Why Newtonsoft? Pin
MSBassSinger2-Oct-23 7:13
professionalMSBassSinger2-Oct-23 7:13 
AnswerRe: Why Newtonsoft? Pin
Nish Nishant2-Oct-23 7:10
sitebuilderNish Nishant2-Oct-23 7:10 
PraiseInteresting... Pin
dandy7229-Sep-23 5:27
dandy7229-Sep-23 5:27 
GeneralRe: Interesting... Pin
Nish Nishant29-Sep-23 7:04
sitebuilderNish Nishant29-Sep-23 7:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.