Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to make DataContractJsonSerializer serialize Dictionaries properly?

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

like image 203
morpheus Avatar asked Dec 30 '10 04:12

morpheus


2 Answers

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

var serializer = new DataContractJsonSerializer(typeOfObj, new DataContractJsonSerializerSettings() {     UseSimpleDictionaryFormat = true  }); 
like image 108
Mr.Wang from Next Door Avatar answered Sep 21 '22 20:09

Mr.Wang from Next Door


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.

like image 41
Josh Avatar answered Sep 18 '22 20:09

Josh