JSON序列化列表<keyvaluepair <string,object =“”>&gt; </keyvaluepair <string,>

时间:2014-01-09 13:31:09

标签: c# json serialization

我在Web API项目中使用了一个Dictionary,它正如JSON中那样序列化:

{"keyname":{objectvalue},"keyname2:"....

由于我有重复的键,我不能再使用Dictionary类型了,现在我正在使用List<KeyValuePair<string,object>>.

但这是以这种方式序列化:

[{"Key":"keyname","Value":"objectvalue"}...

有没有办法让List<KeyValuePair>序列化与字典相同?

感谢。

1 个答案:

答案 0 :(得分:33)

如果您使用Newtonsoft Json.NET库,则可以执行以下操作。

定义转换器以按您希望的方式编写键/值对列表:

class MyConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        List<KeyValuePair<string, object>> list = value as List<KeyValuePair<string, object>>;
        writer.WriteStartArray();
        foreach (var item in list)
        {
            writer.WriteStartObject();
            writer.WritePropertyName(item.Key);
            writer.WriteValue(item.Value);
            writer.WriteEndObject();
        }
        writer.WriteEndArray();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // TODO...
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(List<KeyValuePair<string, object>>);
    }
}

然后使用转换器:

var keyValuePairs = new List<KeyValuePair<string, object>>
                    {
                        new KeyValuePair<string, object>("one", 1),
                        new KeyValuePair<string, object>("two", 2),
                        new KeyValuePair<string, object>("three", 3)
                    };

JsonSerializerSettings settings = new JsonSerializerSettings { Converters = new [] {new MyConverter()} };
string json = JsonConvert.SerializeObject(keyValuePairs, settings);

这会生成[{"one":1},{"two":2},{"three":3}]