In this article I will explain with an example, how to use Serialize method of JavaScriptSerializer class in C# and VB.Net.
This article makes use of .Net version 3.5.
 
 
What is JavaScriptSerializer
JavaScriptSerializer is a class that helps to serialize and deserialize JSON.
Serialization is the process of converting .Net objects into a JSON format, and deserialization is the process of converting JSON data into .Net objects..
This class belongs to the System.Web.Script.Serialization which belongs to the System.Web.Extensions dll.
Serialize Method of JavaScriptSerializer Class
Serialize method serializes an .Net object and converts it to a JSON formatted string.
 
 
Installing and Configuring ASP.Net AJAX Extension 1.0
JavaScriptSerializer class is not available in ASP.Net 3.5, hence you need to install ASP.Net AJAX Extension 1.0 and then add reference of System.Web.Extensions dll.
For more details on install and configure ASP.Net AJAX Extension, please refer my article Install and Configure ASP.Net AJAX Extension.
 
 
Namespaces
You will need to import the following namespace.
C#
using System.Web.Script.Serialization;
 
VB.Net
Imports System.Web.Script.Serialization
 
 
Property Class
The following class consists of two properties.
C#
public class Person
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
 
    private int _age;
    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }
}
 
VB.Net
Public Class Person
    Private _name As String
    Public Property Name As String
        Get
            Return _name
        End Get
        Set(value As String)
            _name = value
        End Set
    End Property
 
    Private _age As Integer
    Public Property Age As Integer
        Get
            Return _age
        End Get
        Set(value As Integer)
            _age = value
        End Set
    End Property
End Class
 
 
Using Serialize Method of JavaScriptSerializer Class in .Net 3.5
First, an object of the Person class is created and values of Name and Age properties are set.
Finally, the person object is serialized into a JSON string using the Serialize method of the JavaScriptSerializer class.
C#
Person person = new Person();
person.Name = "Mudassar Khan";
person.Age = 35;
string json = new JavaScriptSerializer().Serialize(person);
 
VB.Net
Dim person As Person = New Person()
person.Name = "Mudassar Khan"
person.Age = 35
Dim json As String = New JavaScriptSerializer().Serialize(person)
 
 
Screenshot
.Net 3.5: Using Serialize Method of JavaScriptSerializer Class in C# and VB.Net
 
 


Other available versions