2

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?

Goran
  • 383
  • 4
  • 12
  • Don't format the HTML yourself. Use jquery.tmpl. Javascript (code that you write) should be used for logic, not for rendering. – jgauffin Nov 24 '11 at 07:33

4 Answers4

3

You're not returning your List<Product> directly to the client. It's not going over the wire as a List<Product> - there's no such concept at the HTTP level. However, the server-side framework you're using is performing the JSON serialization for you. If you perform serialization first, then the serialized string will then be JSON-serialized, including another level of escaping etc.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Does this means that I just never have to do JSON serializtion, when I send data back to client? Then what is JavaScriptSerializer for? Also, I found lots of texts talking about serializing data before sending it... – Goran Nov 24 '11 at 19:03
  • @Goran: `JavaScriptSerializer` is probably used *by* the framework to serialize your data for you - and in *other* scenarios where you wanted to be able to create JSON it would make sense. It's just that in this case it's done for you implicitly. It's like SOAP calls - you don't usually call `SoapFormatter` yourself... – Jon Skeet Nov 24 '11 at 19:29
1

I think you need to first call $.parseJSON(msg.d) to turn the JSON string into JS Objects, that jQuery will have no problems ot iterate over. You will probably end up with an object like "yourServiceMethodCallNameResult" and that object will have an array of objects (your products).

Pavel Donchev
  • 1,809
  • 1
  • 17
  • 29
1

You havent mentioned how you query for the product list. The problem with JavaScriptSerializer is that it returns a JSON output wrapped in a XML tag, which makes it a XMLObject on the client. You can simply get the inner text content and use $.parseJSON() method to convert it into a JSON object on the client.

An example which queries a WCF service which uses JavaScriptSerializer to serialize a Product list into JSON.

server side:

JavaScriptSerializer js = new JavaScriptSerializer();
List<Product> p = new List<Product>()
{
new Product() { Name = "one", Price = "1", Qnt = "1" },
new Product() { Name = "two", Price = "1", Qnt = "1" },
new Product() { Name = "three", Price = "1", Qnt = "1" },
new Product() { Name = "four", Price = "1", Qnt = "1" },
new Product() { Name = "five", Price = "1", Qnt = "1" },
new Product() { Name = "six", Price = "1", Qnt = "1" }
};
return js.Serialize(p);

client side:

$.get("http://server/service/GetProducts", function (data) {
    var jsonObj = $.parseJSON(data.firstChild.textContent);
    var obj1 = jsonObj[0];
});
Mohib Sheth
  • 1,135
  • 10
  • 22
  • OK, I reaised that `$.parseJSON` will create object out of string, but stil remains the question: Why/When slould I use serialization/parsing, when I can just send list of objects and asp.net do the JSON serialization for me? Thanks! – Goran Nov 24 '11 at 19:23
  • Read this to understand why JSON? http://robtiffany.com/windows-phone-7/windows-phone-7-line-of-business-app-dev-building-a-wcf-rest-json-service – Mohib Sheth Nov 25 '11 at 04:34
  • To make it simple. 1) Its universal and can be used to & from for any platform/language just like XML 2) In respect to XML it gets rid of tags which makes it very small and compact. – Mohib Sheth Nov 25 '11 at 04:36
  • It is interesting text, but i think I wasn't clear enough: OK, I want to use JSON to transfer data from asp.net. But how can I know will it be serialized automaticaly, or do I have to serialize it? I have updated my question with this. – Goran Nov 25 '11 at 07:09
  • @MohibSheth, Thanks for parsing example, but I can chose only one answer. – Goran Nov 25 '11 at 09:40
0

You use JSON to send information over a network. JSON is a more efficient representation of data than XML because it is less verbose. Typically you would serialise a class or whatever into JSON on the server, send it to the client, and then the client deserialises it to JavaScript. Or from JavaScript you serialise it from an object or an array into JSON, send it to the server, and then the server deserialises it there

danwellman
  • 9,068
  • 8
  • 60
  • 88