C#JSON将字典序列化为{key:value,...}而不是{key:key,value:value,...} [英] C# JSON Serialization of Dictionary into {key:value, ...} instead of {key:key, value:value, ...}

查看:182
本文介绍了C#JSON将字典序列化为{key:value,...}而不是{key:key,value:value,...}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to serialize a .Net Dictionary<Key,Value> into JSON with DataContractJsonSerializer that is of the format:

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

我因为没有预定义的输入结构,所以使用字典< K,V>。

I use Dictionary <K,V>, because there is not predefined structure of the inputs.

我很有趣只是为了 DataContractJsonSerializer 结果!我已经找到了一个代理例子,但在输出中还有一个额外的数据,如果字典< K,String>是,逃脱也是假的。

I'm interesting just for DataContractJsonSerializer result! I've already found a "Surrogate" example, but there is an additional "data" in the output, and if the dictionary <K, String> is, the escaping is false too.

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

I've found the solution, what a needed! First of all, a serializable "dictionary" class: (Of course, this sample works just in one way, but I dont't need deserialization)

[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这样做...

Json.NET does this...

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序列化集合

More examples: Serializing Collections with Json.NET

这篇关于C#JSON将字典序列化为{key:value,...}而不是{key:key,value:value,...}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆