问题在于你的BlobItem
type:
public class BlobItem : IBlobItem
{
public BlobItem()
{
TypeXDataDictionary = new TypeXDictionary<IEnumerable<IDataItem>>();
}
[JsonProperty(ItemConverterType = typeof(TypeConverter<IEnumerable<IDataItem>, List<DataItem>>))]
public TypeXDictionary<IEnumerable<IDataItem>> TypeXDataDictionary { get; set; }
}
For TypeXDataDictionary
你指定一个ItemConverterType = typeof(TypeConverter<IEnumerable<IDataItem>, List<DataItem>>)
指示如何反序列化的值TypeXDataDictionary
。然而,这本词典实际上是一本词典的词典:
public class TypeXDictionary<T> : Dictionary<string, TypeYDictionary<T>>
{
}
public class TypeYDictionary<T> : Dictionary<string, T>
{
}
因此它的值不是类型IEnumerable<IDataItem>
,它们属于类型Dictionary<string, IEnumerable<IDataItem>>
并且转换器将无法工作。您需要的是一个项目项目的转换器TypeXDictionary
,可以定义如下:
public class DictionaryValueTypeConverter<TDictionary, TKey, TValue, TValueSerialized> : JsonConverter
where TDictionary : class, IDictionary<TKey, TValue>, new()
where TValueSerialized : TValue
{
public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var surrogate = serializer.Deserialize<Dictionary<TKey, TValueSerialized>>(reader);
if (surrogate == null)
return null;
var dictionary = existingValue as TDictionary ?? new TDictionary();
foreach (var pair in surrogate)
dictionary[pair.Key] = pair.Value;
return dictionary;
}
}
然后应用到BlobItem
如下:
public class BlobItem : IBlobItem
{
public BlobItem()
{
TypeXDataDictionary = new TypeXDictionary<IEnumerable<IDataItem>>();
}
[JsonProperty(ItemConverterType = typeof(DictionaryValueTypeConverter<TypeYDictionary<IEnumerable<IDataItem>>, string, IEnumerable<IDataItem>, List<DataItem>>))]
public TypeXDictionary<IEnumerable<IDataItem>> TypeXDataDictionary { get; set; }
}
Sample fiddle https://dotnetfiddle.net/dxybGa.