Json.NET & C# – How to Seralize an Object ?

One of the ways to serialize an object to JSON string in C# in the Json.NET is using the SerializeObject method defined in the JsonConvert method.

The JsonConvert class provides an easy to use wrapper class and method over the JsonSerializer.

How to Seralize an Object in C# using Json.NET ?

Below is the sample code snippet demonstrating the usage of JsonConvert.SerializeObject method in C# for serialization. The SerializeObject method has 7 overloads option.

public static string SerializeObject(object value);
public static string SerializeObject(object value, params JsonConverter[] converters);
public static string SerializeObject(object value, JsonSerializerSettings settings);
public static string SerializeObject(object value, Formatting formatting);
public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters);
public static string SerializeObject(object value, Type type, JsonSerializerSettings settings);
public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings);
public static string SerializeObject(object value, Type type, Formatting formatting, JsonSerializerSettings settings);

The below code uses the parameterized method which uses the Formatting as the second parameter.

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace ACConsoleCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee
            {
                Name = "Abundantcode",
                IsPermanent = true,
                Departments = new List<string> {"Technology", "Product Engineering"}
            };
            // Serializing the employee object to Json string
            string jsonTxt = JsonConvert.SerializeObject(emp, Formatting.Indented);
            Console.WriteLine(jsonTxt);
            Console.ReadLine();
        }
    }

    public class Employee
    {
        public string Name { get; set; }
        public bool IsPermanent { get; set; }
        // Employee can belong to multiple departments
        public List<string> Departments { get; set; }
    }
}

The output of the above code is

{
  "Name": "Abundantcode",
  "IsPermanent": true,
  "Departments": [
    "Technology",
    "Product Engineering"
  ]
}

2 Comments

Leave Your Comment

Liked this content?. Please spread the word :)