DataContractJsonSerializer should serialize Dictionary<K,V> as a JSON associative array

摘要:DataContractJsonSerializer should serialize Dictionary as a JSON associative array

The DataContractJsonSerializer is not interoperable with the definitive javascript library for json serialization, which is available at http://www.JSON.org/json2.js .

#1 - consider the case of serializing in Javascript, and de-serializing in .NET:

Using that library from within Javascript, it is easy to produce json. This is the javascript code:

var a = {};
a["Red"] = "Rosso";
a["Blue"] = "Blu";
a["Green"] = "Verde";

// use utility class from http://www.JSON.org/json2.js
var json = JSON.stringify(a);
// json = {"Red":"Rosso","Blue":"Blu","Green":"Verde"}

But, this json string cannot be de-serialized by DCJS into a Dictionary. Trying to de-serialize this string using DCJS produces a null object.

#2 - consider the case where a .NET Dictionary is serialized into JSON using DCJS, then de-serialized via the javascript library.

This is the C# code:

[CollectionDataContract]
public class Clazz : Dictionary<String,String> {}

var c1 = new Clazz();
c1["Red"] = "Rosso";
c1["Blue"] = "Blu";
c1["Green"] = "Verde";

Serializing c1 produces this JSON:

[{"Key":"Red","Value":"Rosso"},{"Key":"Blue","Value":"Blu"},{"Key":"Green","Value":"Verde"}]

De-serializing this in Javascript via JSON2.js produces an array of objects, not a dictionary.


Serialization between DataContractJsonSerializer and JSON2.js ought to be reflexive. It should be possible to round-trip between these serializers, in either direction.