Best Way To Serialize and Deserialize Object To JSON In Asp.net

The JavaScriptSerializer class provides a public api to serialize an object to JSON and JSON string to Object. To serialize an object, use the Serialize method. To deserialize a JSON string, use the Deserialize<T> or DeserializeObject methods.

Namespace:   System.Web.Script.Serialization
Assembly:  System.Web.Extensions (in System.Web.Extensions.dll)

C# Example for Serializing to JSON

public static string ConvertToJson(object obj)
{
return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(obj);
}

C# Example for Deserialize JSON To Object

public class Person
{
public int PersonID { get; set; }
public string Name { get; set; }
public bool Registered { get; set; }
}
public class Example
{
public static List<Person> Deserialize(string data)
{
var serializer = new JavaScriptSerializer();
return serializer.Deserialize<List<Person>>(serializedResult);
}
}

Leave a Reply

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