我试图以不同的方式转换特定类的特定IDictionary
字段。我当时正在考虑基于属性来执行此操作,但是看起来它行不通。
能否以某种方式获得与CustomAttribute
中的类型相关联的CanConvert
?
[CustomAttribute]
public IDictionary<string, string> AdditionalData { get; set; }
// Custom converter for CustomAttribute
public override bool CanConvert(Type objectType)
{
return System.Attribute.GetCustomAttributes(objectType).Any(v => v is CustomAttribute);
}
答案 0 :(得分:3)
如果要使用属性将转换器应用于特定属性,只需使用[JsonConverter]
属性。真的不需要发明自己的东西。
[JsonConverter(typeof(YourCustomConverterClass))]
public IDictionary<string, string> AdditionalData { get; set; }
请注意,如果您应用[JsonConverter]
属性,则不再需要将该转换器的实例传递给序列化器。另外,不会为该属性调用转换器的CanConvert
方法,因为Json.Net已经知道您要与它一起使用转换器。