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.
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:
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.