Cloud Training (Online)

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);

Senthil Kumar B
Senthil Kumar is a former Microsoft MVP (Most Valuable Professional). He is a Co-Author of the book "Windows 10 Development Recipes using JavaScript and CSS" for Apress Publication. He is a technical presenter, blogger, mentor and a Geek.  Senthil is a regular speaker is various local user groups. He has presented at conferences like Great Indian Developer Summit (GIDS) & Microsoft DevCamps. You can reach out to him via his Twitter handle @isenthil.