C# Tips and Tricks #14 – Convert C# object to Json string

You can easily convert the C# object to JSON string by using the Newtonsoft.Json NuGet package which is one of the popular serializer for the .NET Developers.

How to convert C# object to JSON string in C# ?

1. Ensure that the Newtonsoft.Json NuGet package is installed in the project.

SNAGHTML1f736cbb

2. Assuming that you have a C# class with the following properties and you want them to be serialized.

public class Employee
   {
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public DateTime JoinedDate { get; set; }
    }

3. You can serialize or convert the C# object to Json string with the SerializeObject method

Employee emp = new Employee();
emp.FirstName = "Senthil";
emp.LastName = "Balu";
emp.JoinedDate = DateTime.Now;
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(emp);

Here’s the full code snippet demonstrating how to serialize the C# class and get the Json string.

using System;
using System.Collections.Generic;

namespace ConsoleApp1
 {
     public class Employee
     {
         public string FirstName { get; set; }
         public string LastName { get; set; }
         public DateTime JoinedDate { get; set; }
     }
     class Program
     {
         static void Main(string[] args)
         {
             Employee emp = new Employee();
             emp.FirstName = "Senthil";
             emp.LastName = "Balu";
             emp.JoinedDate = DateTime.Now;
             var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(emp);
             Console.WriteLine(jsonString);

            Console.ReadLine();
         }
     }
 }
image

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...