This is one of the most widely used and very useful script that you could use in your web services/ WCF services/ Handlers or any place wherein you require a JSON string to be passed to the client/ consumer.
We make use of the Serialize method in JavaScriptSerializer class in C# under the following namespace:
using System.Web.Script.Serialization;
The code snippet below show how its done:
//Namespace for the JavascriptSerializer object
using System.Web.Script.Serialization;
public string GenerateJSONString(List<myObject> myCustomList)
{
//Initialize the JavascriptSerializer object
JavaScriptSerializer serializer = new JavaScriptSerializer();
//Initialize a stringbuilder object to hold the final JSON output
StringBuilder jsonBuilder = new StringBuilder();
//Generate the JSON string
serializer.Serialize(myCustomList, jsonBuilder);
//Return the JSON string
return Convert.ToString(jsonBuilder);
}
This code is just a framework to get to know that the JavascriptSerializer could help you generate JSON string with ease.
In the client side, you could use jQuery.parseJSON(JSONstring); and then parse this JSON string using the myObject properties. Remeber that parseJSON was added in jQuery v1.4.1.
[…] Generate JSON String Output in C# […]