views:

69

answers:

2

I'm working on an ASP.Net MVC project and have been learning a few little tricks with JSON objects that made me scratch my head for quite a while. For example, ensuring that when I call $.getJSON() from jQuery, I actually need to make sure my JSON is returning an object, not just a string value (well, D'uh! right?).

What are some of the key things to watch out for when working with JSON objects and responses in your experience? I'm particularly interested in ASP.Net, but could be any language.

+3  A: 

One nasty json bug that has bitten me occurred when I used .Net serialization within a WCF project to produce JSon responses for another service. It was perfectly legal JSon according to an online verifier, but the recipient wouldn't swallow it.

It turned out that the order of the contents mattered. According to JSon spec the order should not matter, but apparently the consumer at the other end used some kind of custom parser that choked when it didn't find a certain field at the top. The serializer put the contents in alphabetical order.

I despaired for a little while, until I found out that I could give the serializer an explicit ordering via data contracts. Problem solved.

Example:

[DataMember(Order = 1)] //<-- thank Zod this exists!
public List<Foo> MyFoos { get; set; }

puts an array 'MyFoos' at the top of the JSon response.

Note: if you do this, make sure to give each data member an ordering, because data members without an order number will still float to the top.

cfern
+1  A: 

Never send line feeds or new lines. Also because of characer escaping. IF your using the .NET Json searilzer then it should take care of these things for you but if your doing it yourself you need to be carefull.

Also I noticed sometimes strings are sent/retrieve with leading spaces, so make sure you call .trim()!

TAkinremi