When using DataContractJsonSerializer to serialize a dictionary, like so:
[CollectionDataContract]
public class Clazz : Dictionary<String,String> {}
....
var c1 = new Clazz();
c1["Red"] = "Rosso";
c1["Blue"] = "Blu";
c1["Green"] = "Verde";
Serializing c1 with this code:
var dcjs = new DataContractJsonSerializer(c1.GetType());
var json = new Func<String>(() =>
{
using (var ms = new System.IO.MemoryStream())
{
dcjs.WriteObject(ms, c1);
return Encoding.ASCII.GetString(ms.ToArray());
}
})();
...produces this JSON:
[{"Key":"Red","Value":"Rosso"},
{"Key":"Blue","Value":"Blu"},
{"Key":"Green","Value":"Verde"}]
But, this isn't a Javascript associative array. If I do the corresponding thing in javascript: produce a dictionary and then serialize it, like so:
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);
The result is:
{"Red":"Rosso","Blue":"Blu","Green":"Verde"}
How can I get DCJS to produce or consume a serialized string for a dictionary, that is compatible with JSON2.js ?
I know about JavaScriptSerializer from ASP.NET. Not sure if it's very WCF friendly. Does it respect DataMember, DataContract attributes?