问题描述
如何使 Json.NET 序列化程序将 IDictionary<,>
实例序列化为具有键/值属性的对象数组?默认情况下,它将 Key 的值序列化为 JSON 对象的属性名称.
How can I make Json.NET serializer to serialize IDictionary<,>
instance into array of objects with key/value properties?By default it serializes the value of Key into JSON object's property name.
基本上我需要这样的东西:
Basically I need something like this:
[{"key":"some key","value":1},{"key":"another key","value":5}]
代替:
{{"some key":1},{"another key":5}}
我尝试将 KeyValuePairConverter
添加到序列化程序设置,但没有效果.(我发现对于 IDictionary<>
的类型,此转换器被忽略,但我无法轻易更改对象的类型,因为它们是从其他库接收的,因此从 IDictionary<>
到 ICollection<KeyValuePair<>>
不适合我.)
I tried to add KeyValuePairConverter
to serializer settings but it has no effect. (I found this converter is ignored for type of IDictionary<>
but I cannot easily change the type of my objects as they are received from other libraries, so changing from IDictionary<>
to ICollection<KeyValuePair<>>
is not option for me.)
推荐答案
我能够让这个转换器工作.
I was able to get this converter to work.
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();
}
}
以下是使用转换器的示例:
Here is an example of using the converter:
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}]
这篇关于序列化字典<,>作为 Json.NET 中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!