C# Tips and Tricks #15 – Convert C# object to Json string using JavaScriptSerializer

In one of my previous blog posts , we looked at converting c# object to Json string using the Newtonsoft.Json Nuget. In this blog post , lets have a look at the JavaScriptSerializer to perform the same task.

How to Serialize C# object to Json string using JavaScriptSerializer?

The JavaScriptSerializer is defined in the System.Web.Script.Serialization namespace and note the usage of System.Web namespace… It is highly recommended that you use JSON.NET instead this demo is just to demonstrate that this one is also possible.

To convert the employee object to the Json object , you can use the Serialize method defines in the JavaScriptSerializer class.

var jsonString = new JavaScriptSerializer().Serialize(emp);

imageHere’s the complete code snippet that is used for this demo.

using System;
using System.Web.Script.Serialization;
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 = new JavaScriptSerializer().Serialize(emp);
            Console.WriteLine(jsonString);

            Console.ReadLine();
        }
    }
}

Leave a Reply

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