I am a little confused about when do I have to serialize objects using JSON serialization and when it is not necessary (even needless).
I've spent several days trying to send a list of simple objects using jQuery.ajax and JSON. I have a class named Product:
public class Product
{
public string Name;
public string Qnt;
public string Price;
}
and a web method that returns a list filled with Products
List<Product> p = new List<Product>();
I used System.Web.Script.Serialization.JavaScriptSerializer
to serialize this list in JSON and send it to the client as a string, where i format it using jQuery
$.each(msg.d, function (index, Product) {
$('#details').append('<p>Name: ' + Product.Name
+ '<br />Quantity: ' + Product.Qnt
+ '<br />Price: ' + Product.Price + '</p>');
});
...and it wouldn't work... Because at the client side, I just get a long string (it would be parsed character by character, when I use $.each) - I learned that it should be parsed first
It took time until I realised that I just have to return it as a List of Product objects, without serialization, and client gets list of products in perfect JSON format!
EDIT: What I actually don't understand: if I serialize my list, it returns JSON formated string that have to be parsed before I can use it. If i don't serialize my list, it returns the same data, but as an object, not a string, so I can use it right away. How can I know do I have to use JSON serialization on my data, or it will always be done by framework?