![](/img/trans.png)
[英]How to specify custom json converter for the generic argument of a property type
[英]Custom generic json converter not called
我有一个带有抽象键和值的字典的自定义 JsonConverter:
public class DictionaryJsonConverter<TKey, TValue> : JsonConverter<Dictionary<TKey, TValue>>
我使用它如下:
[JsonConverter(typeof(DictionaryJsonConverter<ServerDevice, long>))]
public static Dictionary<ServerDevice, long> KnownServers { get; set; }
但是没有调用 read 和 write 方法。 我错过了什么吗?
错误再现示例: https://dotnetfiddle.net/2VakI3 (DotNetFiddle 中不编译)
我不保证读取或写入方法是正确的,因为我从未见过结果。
我相信问题是你不能只做JsonConvert.SerializeObject(SomeDictionaryThatHappensToBeInAProperty)
,因为那样它就看不到JsonConverterAttribute
。 它所知道的只是它从某个地方得到了一个字典。 因此,它将使用它拥有的任何JsonConverter
用于字典。
因此,您需要明确告诉 Json.NET 使用哪个转换器。 从您的评论中,您似乎找到了一种方法来告诉 Json.NET 使用哪个转换器(通过将转换器存储在JsonSerializerSettings
实例的Converters
属性中并将其作为参数提供给JsonConvert.SerializeObject
)。
但是,如果您的属性位于 class 中,并且您序列化了该 class 的实例,那么它可以正常工作,因为它会看到属性上的属性并知道要使用哪个JsonConverter
。 例如:
public class Test {
[JsonConverter(typeof(DictionaryJsonConverter<ServerDevice, long>))]
public Dictionary<ServerDevice, long> KnownServers { get; set; }
}
...
static void Main(string[] args) {
Test test = new Test() {
KnownServers = new Dictionary<ServerDevice, long>() {
{ new ServerDevice() { ID = "a", Name = "A", IPAddress = IPAddress.Any }, 1 },
{ new ServerDevice() { ID = "b", Name = "B", IPAddress = IPAddress.Any }, 2 },
{ new ServerDevice() { ID = "c", Name = "C", IPAddress = IPAddress.Any }, 3 },
}
};
// This correctly uses DictionaryJsonConverter for KnownServers
Console.WriteLine(JsonConvert.SerializeObject(test));
}
但是,此方法可能不是您想要的,因为它显然也会“围绕”该属性序列化Test
object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.