是否可以使用以下格式的DataContractJsonSerializer将.Net Dictionary <Key,Value>序列化为JSON :
{
key0:value0,
key1:value1,
...
}
我使用字典<K,V>,因为没有预定义的输入结构。
我对DataContractJsonSerializer的结果很感兴趣!我已经找到一个“代理”示例,但是输出中还有一个附加的“数据”,如果字典<K,String>是,转义也是假的。
我已经找到了解决方案,需要什么!首先,一个可序列化的“字典”类:(当然,该示例仅以一种方式工作,但是我不需要反序列化)
[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"
}
}
DataContractJsonSerializer
什么特定原因上?每次进行比较时(这是几次:我非常“喜欢”我的序列化器),这是.NET中最不推荐使用的JSON工具。我总是看JavaScriptSerializer或JSON.Net