here i attach a sample code. they used JavaScriptSerializer to generate data in json format and send back the data to client
GetPersons() has been called by jquery ajax function. code here
$.ajax({
type: "POST",
url: "Default.aspx/GetPersons",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
[WebMethod()]
public static string GetPersons()
{
List<person> persons = new List<person>()
{
new Person { UId = 1, Name = "Brij", Address = "Noida"},
new Person { UId = 2, Name = "Rahul", Address = "New Delhi" },
new Person { UId = 3, Name = "John0", Address = "Chris"}
};
JavaScriptSerializer ser = new JavaScriptSerializer();
return ser.Serialize(persons);
}
when a method is decorated by WebMethod then data is generated in json format automatically when they are return. if you guys look it closely
then u can see GetPersons() string instead of List. why some one return string instead of List . if they would return List
then data need not to be generated manually in json format. am i right?
so i just need to know why people use JavaScriptSerializer to generate data in json format. so please tell me what kind of situation one has to use
JavaScriptSerializer to generate data manually in json format?
please discuss in detail…….thanks
JSON serialization is not mandatory. You could return a list of comma-separated value pairs. The difference in that the list would have to be parsed on the client to turn it back into an array or data object. The beauty of JSON is it is ALREADY a native JavaScript object.
This becomes more important when data structures become more complex.