开发者

.NET: Can I use DataContractJsonSerializer to serialize to a JSON associative array?

开发者 https://www.devze.com 2022-12-29 23:33 出处:网络
When using DataContractJsonSerializerto serialize a dictionary, like so: [CollectionDataContract] public class Clazz : Dictionary<String,String> {}

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";开发者_JAVA百科
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?


What it is doing is perfectly sensible, the JSON it produces is a reasonable representation of a .net dictionary in JSON. If you wanted the JSON output you describe you would need to serialise a 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 JavaScript associative arrays are not really arrays, you are simply exploiting the fact that object["key"] is another way of refering to object.key. As such when it serialises a .net dictionary to JSON it produces an array of key/value pair objects, exactly as you would expect.


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

Please vote it up.

0

精彩评论

暂无评论...
验证码 换一张
取 消