Convert an Object to JSON in C#: A Comprehensive Guide

Category > CSHARP || Published on : Monday, March 13, 2023 || Views: 142 || C# JSON Newtonsoft.Json Serialization Object-Oriented Programming.


Learn how to easily convert an object to JSON in C# using the Newtonsoft.Json package. This article covers the basics of serializing objects into JSON format, customizing the serialization process, and using custom converters.

JSON (JavaScript Object Notation) is a lightweight data format that is commonly used for data exchange between client and server. In C#, the Newtonsoft.Json package provides a simple and efficient way to convert an object to JSON.

To convert an object to JSON in C#, we need to use the JsonSerializer class from the Newtonsoft.Json namespace. The JsonSerializer class provides various methods to serialize an object into JSON format.

First, let's create a simple C# class that we want to convert to JSON:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

To convert an instance of this class to JSON, we can use the SerializeObject method of the JsonSerializer class:

Person person = new Person { Name = "John Doe", Age = 30 };
string json = JsonConvert.SerializeObject(person);

In the above code, we first create an instance of the Person class with some sample data. We then call the static SerializeObject method of the JsonConvert class and pass in the person object as a parameter. The method returns a JSON string representation of the object.

We can also customize the serialization process using the JsonSerializerSettings class. For example, we can control the formatting of the output JSON by setting the Formatting property:

Person person = new Person { Name = "John Doe", Age = 30 };
JsonSerializerSettings settings = new JsonSerializerSettings
{
    Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(person, settings);

In the above code, we create an instance of the JsonSerializerSettings class and set the Formatting property to Indented, which formats the output JSON with indentation for better readability.

We can also customize the serialization process by specifying custom converters. For example, let's say we want to serialize a DateTime object as a Unix timestamp:

public class UnixDateTimeConverter : DateTimeConverterBase
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        long seconds = ((DateTime)value - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks / TimeSpan.TicksPerSecond;
        writer.WriteValue(seconds);
    }
}

Person person = new Person { Name = "John Doe", Age = 30, Birthday = new DateTime(1990, 1, 1) };
JsonSerializerSettings settings = new JsonSerializerSettings
{
    Converters = new List<JsonConverter> { new UnixDateTimeConverter() }
};
string json = JsonConvert.SerializeObject(person, settings);

In the above code, we create a custom converter called UnixDateTimeConverter that overrides the WriteJson method to convert a DateTime object to a Unix timestamp. We then add the converter to the Converters property of the JsonSerializerSettings class.

In conclusion, converting an object to JSON in C# is a simple process using the Newtonsoft.Json package. The JsonSerializer class provides various methods and settings to customize the serialization process to meet specific requirements.