serialize derived class to json in csharp

To serialize a derived class (i.e. a class that inherits from another class) to JSON in C#, we can use the Newtonsoft.Json library. Here's an example of how to do this:

main.cs
using Newtonsoft.Json;

// Base class
public class Animal
{
    public string Name { get; set; }
}

// Derived class
public class Dog : Animal
{
    public int Age { get; set; }
}

// Serialization
Dog dog = new Dog { Name = "Fido", Age = 3 };
string json = JsonConvert.SerializeObject(dog);
292 chars
18 lines

In this example, we have a base class Animal and a derived class Dog that inherits from Animal. To serialize an instance of Dog to JSON, we simply use the JsonConvert.SerializeObject method from the Newtonsoft.Json library. This method serializes the object to a JSON string, which we can then use however we like.

Note that we didn't have to do anything special to handle the fact that Dog is a derived class – the JsonConvert.SerializeObject method automatically takes care of serializing all of the properties of the object, including those inherited from Animal.

gistlibby LogSnag