序列化字典<,>作为Json.NET中的数组

时间:2013-08-22 15:52:18

标签: json.net

如何让Json.NET序列化程序将IDictionary<,>实例序列化为具有键/值属性的对象数组? 默认情况下,它将Key的值序列化为JSON对象的属性名称。

基本上我需要这样的东西:

[{"key":"some key","value":1},{"key":"another key","value":5}]

而不是:

{{"some key":1},{"another key":5}}

我尝试将KeyValuePairConverter添加到序列化程序设置,但它没有任何效果。 (我发现IDictionary<>的类型会忽略此转换器,但我无法轻易更改从其他库收到的对象类型,因此从IDictionary<>更改为ICollection<KeyValuePair<>>不是选项对我来说。)

2 个答案:

答案 0 :(得分:5)

我能够让这个转换器工作。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public class CustomDictionaryConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (typeof(IDictionary).IsAssignableFrom(objectType) || 
                TypeImplementsGenericInterface(objectType, typeof(IDictionary<,>)));
    }

    private static bool TypeImplementsGenericInterface(Type concreteType, Type interfaceType)
    {
        return concreteType.GetInterfaces()
               .Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        Type type = value.GetType();
        IEnumerable keys = (IEnumerable)type.GetProperty("Keys").GetValue(value, null);
        IEnumerable values = (IEnumerable)type.GetProperty("Values").GetValue(value, null);
        IEnumerator valueEnumerator = values.GetEnumerator();

        writer.WriteStartArray();
        foreach (object key in keys)
        {
            valueEnumerator.MoveNext();

            writer.WriteStartObject();
            writer.WritePropertyName("key");
            writer.WriteValue(key);
            writer.WritePropertyName("value");
            serializer.Serialize(writer, valueEnumerator.Current);
            writer.WriteEndObject();
        }
        writer.WriteEndArray();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

以下是使用转换器的示例:

IDictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("some key", 1);
dict.Add("another key", 5);

string json = JsonConvert.SerializeObject(dict, new CustomDictionaryConverter());
Console.WriteLine(json);

这是以上的输出:

[{"key":"some key","value":1},{"key":"another key","value":5}]

答案 1 :(得分:2)

想出另一种方法 - 您可以创建自定义ContractResolver并在(de)序列化之前将其设置为JsonSerializerSettings。下面的内容来自内置CamelCasePropertyNamesContractResolver以将序列化属性名称转换为驼峰大小写,但如果您不想修改名称,则可以从DefaultContractResolver派生。

public class DictionaryFriendlyContractResolver : CamelCasePropertyNamesContractResolver
{
    protected override JsonContract CreateContract(Type objectType)
    {
        if (objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(IDictionary<,>))
            return new JsonArrayContract(objectType);
        if (objectType.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>)))
            return new JsonArrayContract(objectType);
        return base.CreateContract(objectType);
    }
}

用法:

var cfg = new JsonSerializerSettings();
cfg.ContractResolver = new DictionaryFriendlyContractResolver();
string json = JsonConvert.SerializeObject(myModel, cfg);