Any way to make DataContractJsonSerializer serialize Dictionaries properly?

.NetWcfSerialization

.Net Problem Overview


The DataContractJsonSerializer is not able to serialize Dictionaries properly.

Whereas JavaScriptSerializer serializes Dictionaries as {"abc":"xyz","def":42} for example, the DataContractJsonSerializer gives [{"Key":"abc","Value":"xyz"},{"Key":"def","Value":42}] instead.

This is really problematic and I want to know how can I serialize Dictionary objects correctly in my WCF service. I am looking for a solution that would require least amount of effort.

ref: http://msdn.microsoft.com/en-us/library/bb412170.aspx

This is the workaround I finally used to serilize dictionaries properly in WCF: http://social.msdn.microsoft.com/forums/en-US/wcf/thread/765f1569-0422-4471-8ec2-1d03b2026771

.Net Solutions


Solution 1 - .Net

Using DataContractJsonSerializerSettings (available since .NET 4.5) can do this for you:

var serializer = new DataContractJsonSerializer(typeOfObj, new DataContractJsonSerializerSettings()
{
    UseSimpleDictionaryFormat = true 
});

Solution 2 - .Net

Unfortunately this appears to be by-design, according to the section "Collections, Dictionaries, and Arrays" at http://msdn.microsoft.com/en-us/library/bb412170.aspx

> All collections, dictionaries, and arrays are represented in JSON as arrays.

Solution 3 - .Net

Although this will in most cases cause a major rewrite and thus not be feasible you can let your WCF service interface accept and return Stream in which case you can take full control of serialization. This way you can use JavaScriptSerializer, JSON.NET or ServiceStack.JSON to perform the actual serialization and these serializers actually deals with a dictionaries in a more sensible way.

Solution 4 - .Net

DataContractJsonSerializerSettings has the UseSimpleDictionaryFormat property now and it serializes dictionaries the way you'd expect.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmorpheusView Question on Stackoverflow
Solution 1 - .NetMr.Wang from Next DoorView Answer on Stackoverflow
Solution 2 - .NetJoshView Answer on Stackoverflow
Solution 3 - .NetfaesterView Answer on Stackoverflow
Solution 4 - .NetColinView Answer on Stackoverflow