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

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

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...