C#JSON将字典序列化为{key:value,…}而不是{key:key,value:value,…}

是否可以使用DataContractJsonSerializer将.Net Dictionary <Key,Value>序列化为JSON,格式为:

{ key0:value0, key1:value1, ... } 

我使用Dictionary <K,V>,因为没有预定义的input结构。

我只是为DataContractJsonSerializer结果而感兴趣! 我已经find了一个“Surrogate”的例子,但是输出中还有一个额外的“数据”,如果字典<K,String>是,那么转义也是错误的。


我find了解决scheme,需要什么! 首先,一个可序列化的“字典”类:(当然,这个示例只是以一种方式工作,但是我不需要反序列化)

 [Serializable] public class MyJsonDictionary<K, V> : ISerializable { Dictionary<K, V> dict = new Dictionary<K, V>(); public MyJsonDictionary() { } protected MyJsonDictionary( SerializationInfo info, StreamingContext context ) { throw new NotImplementedException(); } public void GetObjectData( SerializationInfo info, StreamingContext context ) { foreach( K key in dict.Keys ) { info.AddValue( key.ToString(), dict[ key ] ); } } public void Add( K key, V value ) { dict.Add( key, value ); } public V this[ K index ] { set { dict[ index ] = value; } get { return dict[ index ]; } } } 

用法:

 public class MainClass { public static String Serialize( Object data ) { var serializer = new DataContractJsonSerializer( data.GetType() ); var ms = new MemoryStream(); serializer.WriteObject( ms, data ); return Encoding.UTF8.GetString( ms.ToArray() ); } public static void Main() { MyJsonDictionary<String, Object> result = new MyJsonDictionary<String, Object>(); result["foo"] = "bar"; result["Name"] = "John Doe"; result["Age"] = 32; MyJsonDictionary<String, Object> address = new MyJsonDictionary<String, Object>(); result["Address"] = address; address["Street"] = "30 Rockefeller Plaza"; address["City"] = "New York City"; address["State"] = "NY"; Console.WriteLine( Serialize( result ) ); Console.ReadLine(); } } 

结果是:

 { "foo":"bar", "Name":"John Doe", "Age":32, "Address":{ "__type":"MyJsonDictionaryOfstringanyType:#Json_Dictionary_Test", "Street":"30 Rockefeller Plaza", "City":"New York City", "State":"NY" } } 

Json.NET这样做…

 Dictionary<string, string> values = new Dictionary<string, string>(); values.Add("key1", "value1"); values.Add("key2", "value2"); string json = JsonConvert.SerializeObject(values); // { // "key1": "value1", // "key2": "value2" // } 

更多示例: 使用Json.NET序列化集合

DataContractJsonSerializer上使用属性UseSimpleDictionaryFormat并将其设置为true

工作:)

我用这个代码使用了开箱即用的MVC4(注意ToDictionary的两个参数)

  var result = new JsonResult() { Data = new { partials = GetPartials(data.Partials).ToDictionary(x => x.Key, y=> y.Value) } }; 

我得到了预期的结果:

 {"partials":{"cartSummary":"\u003cb\u003eCART SUMMARY\u003c/b\u003e"}} 

重要 :MVC4中的WebAPI使用开箱即用的JSON.NET序列化,但标准的Web JsonResult操作结果不会。 因此,我build议使用自定义的ActionResult来强制JSON.NET序列化。 你也可以得到很好的格式

这是一个简单的动作JsonNetResult

http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx

序列化date时,您将看到不同之处(并确保您使用的是正确的):

微软的方式:

  {"wireTime":"\/Date(1355627201572)\/"} 

JSON.NET方式:

  {"wireTime":"2012-12-15T19:07:03.5247384-08:00"} 

不幸的是,这在DataContractJsonSerializer的最新版本中是不可能的。 请参阅: http : //connect.microsoft.com/VisualStudio/feedback/details/558686/datacontractjsonserializer-should-serialize-dictionary-kv-as-a-json-associative-array

目前build议的解决方法是使用JavaScriptSerializer,如上面的Mark所build议的。

祝你好运!