.NET: Can DataContractJsonSerializer be used to serialize to a JSON associative array?

When using DataContractJsonSerializer to serialize a dictionary like:

[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());
            }
        })();

      

... creates this JSON:

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

      


But this is not a Javascript associative array. If I do the relevant thing in javascript: create 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);

      

Result:

{"Red":"Rosso","Blue":"Blu","Green":"Verde"}

      

How can I get DCJS to create or use a serialized string for a dictionary that is JSON2.js compatible ?


I know about JavaScriptSerializer from ASP.NET. Not sure if this is very WCF. Does it mean DataMember, DataContract attributes?

+2


a source to share


2 answers


I raised a bug on MS Connect for the above behavior .



Please vote.

0


a source


What it does is perfectly sane, the JSON it produces is a sane representation of a .net dictionary in JSON. If you want to get the JSON description that you need to describe, you will need to serialize the class like

public class ColourThingy
{
      public string Red {get;set;}
      public string Blue {get;set;}
      public string Green {get;set;}
}
ColourThingy MyColourThingy = new ColourThingy();
MyColourThingy.Red = "Rosso";
...

      



Remember that JavaScript associative arrays are not arrays, you are simply using the fact that the ["key"] object is another way to refer to object.key. So when it serializes the .net dictionary to JSON, it creates an array of key / value pair objects as you would expect.

+2


a source







All Articles