我能讓這個轉換器工作。
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}]
它會更容易(和更完整),檢查非通用'System.Collections.IDictionary'代替。通用接口通常擴展非通用接口。另外,你的'TypeImplementsGenericInterface()'方法可以用Any()而不是'Where()。FirstOrDefault()!= null'來簡化。 –
雖然它會很好,但IDictionary實際上不會擴展非泛型的IDictionary接口。請參閱[文檔](http://msdn.microsoft.com/en-us/library/s4ys34ea.aspx)。但是,爲了完整起見,我編輯了我的答案,以添加對「IDictionary」的支持,並納入了關於簡化「TypeImplementsGenericInterface()'方法的其他建議。謝謝! –
啊對了,我忘了那個。更正,_immutable_通用接口通常擴展相應的_immutable_非通用接口,不幸的是它不適用於此。 –