Any way to get DataContractJsonSerializer to correctly serialize dictionaries?

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.

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

+42
serialization wcf
Dec 30 '10 at 4:24
source share
4 answers

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

 var serializer = new DataContractJsonSerializer(typeOfObj, new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true }); 
+42
Dec 01
source share

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.

+28
Dec 30 '10 at 4:44
source share

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.

+8
Nov 03 2018-11-11T00:
source share

DataContractJsonSerializerSettings now has the UseSimpleDictionaryFormat property, and it serializes the dictionaries as you expected.

+3
Nov 21 '14 at 1:33
source share



All Articles