问题描述
在使用 DataContractJsonSerializer 的连载一本字典,像这样:
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";
序列化这个code C1:
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());
}
})();
...产生此JSON:
...produces this JSON:
[{"Key":"Red","Value":"Rosso"},
{"Key":"Blue","Value":"Blu"},
{"Key":"Green","Value":"Verde"}]
不过,这不是一个Javascript关联数组。如果我在JavaScript相应的事情:生产一本字典,然后序列化,像这样:
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);
结果是:
{"Red":"Rosso","Blue":"Blu","Green":"Verde"}
我怎样才能得到DCJS生产或消费序列化字符串的字典,这是 JSON2兼容。 JS ?
我知道 JavaScriptSerializer 从ASP.NET。不知道这是非常WCF友好。是否尊重数据成员,DataContract属性?
I know about JavaScriptSerializer from ASP.NET. Not sure if it's very WCF friendly. Does it respect DataMember, DataContract attributes?
推荐答案
我提出一个错误在MS连接为我上面描述的行为。
请投它。
这篇关于.NET:我可以使用DataContractJsonSerializer序列化到JSON关联数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!