Any way to make DataContractJsonSerializer serialize Dictionaries properly?
Solution 1:
Using DataContractJsonSerializerSettings (available since .NET 4.5) can do this for you:
var serializer = new DataContractJsonSerializer(typeOfObj, new DataContractJsonSerializerSettings()
{
UseSimpleDictionaryFormat = true
});
Solution 2:
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:
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:
DataContractJsonSerializerSettings
has the UseSimpleDictionaryFormat
property now and it serializes dictionaries the way you'd expect.