Saturday, November 13, 2010

We've all had our problems serializing .NET dictionaries. Specifically with the XmlSerializer. Everyone has saw that dreaded yellow screen of death or perpetual stack trace...

// post stack trace.

Serialization using json

There are 2 choices we have here. The legacy JavaScriptSerializer and DataContractSerializer. The legacy implementation will allow you to serialize more complex data strucutures, but at a cost. Here's the output of the legacy serializer.

// show output.

You may be thinking "no big deal" right?

Well lets take a look at what the DataContractJsonSerializer outputs

// show output.

As you might have guessed, the latter can be more readily consumed client side. It takes the names of the target objects properties into consideration, which is what one would expect.

Wrap up

Use the legacy serializer when you don't care about the output or you want to serialize nested collections without getting yelled at by the runtime.

Use the newer WCF based serializer when you want more user friendly javascript to work with.

The problem with json serialization

Notice that nothing about types when mentioned by the output of neither the legacy or WCF based serializers. That would present itself as a problem for most. In my case, it broke my equality comparison because as we all know, one rudimentary philosophy of equality is that the objects in question must be of the same type.

XmlSerializer to the rescue

No comments:

Post a Comment