DataContractJsonSerializer cannot correctly serialize dictionaries.
While the JavaScriptSerializer serializes dictionaries like {"abc":"xyz","def":42} for example, DataContractJsonSerializer gives [{"Key":"abc","Value":"xyz"},{"Key":"def","Value":42}] instead.
{"abc":"xyz","def":42}
[{"Key":"abc","Value":"xyz"},{"Key":"def","Value":42}]
This is really problematic, and I want to know how to properly serialize Dictionary objects in my WCF service. I am looking for a solution that requires minimal effort.
ref: http://msdn.microsoft.com/en-us/library/bb412170.aspx
This is a workaround that I finally used to correctly serialize dictionaries in WCF: http://social.msdn.microsoft.com/forums/en-US/wcf/thread/765f1569-0422-4471-8ec2-1d03b2026771
Using DataContractJsonSerializerSettings (available since .NET 4.5) can do this for you:
var serializer = new DataContractJsonSerializer(typeOfObj, new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true });
Unfortunately, this looks like a design in accordance with the "Collections, Dictionaries and Arrays" section at http://msdn.microsoft.com/en-us/library/bb412170.aspx
All collections, dictionaries and arrays are represented in JSON as arrays.
Although this in most cases will cause serious correspondence and therefore will not be feasible, you can allow your WCF service interface to receive and return Stream , in which case you can completely control serialization. That way you can use JavaScriptSerializer , JSON.NET or ServiceStack.JSON to do the actual serialization, and these serializers actually deal with dictionaries in a more reasonable way.
Stream
JavaScriptSerializer
DataContractJsonSerializerSettings now has the UseSimpleDictionaryFormat property, and it serializes the dictionaries as you expected.
DataContractJsonSerializerSettings
UseSimpleDictionaryFormat