C# 未调用自定义通用json转换器
我有一个自定义JsonConverter,用于具有抽象键和值的字典:C# 未调用自定义通用json转换器,c#,json.net,C#,Json.net,我有一个自定义JsonConverter,用于具有抽象键和值的字典: public class DictionaryJsonConverter<TKey, TValue> : JsonConverter<Dictionary<TKey, TValue>> 公共类字典JsonConverter:JsonConverter 我的用法如下: [JsonConverter(typeof(DictionaryJsonConverter<ServerDevice
public class DictionaryJsonConverter<TKey, TValue> : JsonConverter<Dictionary<TKey, TValue>>
公共类字典JsonConverter:JsonConverter
我的用法如下:
[JsonConverter(typeof(DictionaryJsonConverter<ServerDevice, long>))]
public static Dictionary<ServerDevice, long> KnownServers { get; set; }
[JsonConverter(类型(字典JsonConverter))]
公共静态字典Known服务器{get;set;}
但是既不调用read方法也不调用write方法。我错过什么了吗
错误再现示例:
(不在DotNetFiddle中编译)
我不能保证读或写方法是正确的,因为我从来没有看到过结果。我认为问题在于你不能只做
jsonvert.SerializeObject(somedictionarythappenstobeinproperty)
,因为那样它就看不到jsonverterattribute
。它所知道的只是从某处得到了一本字典。因此,它将使用字典中的JsonConverter
因此,您需要明确地告诉Json.NET要使用哪个转换器。从您的评论中,您似乎找到了一种告诉Json.NET要使用哪个转换器的方法(将转换器存储在JsonSerializerSettings
实例的converts
属性中,并将其作为JsonConvert.SerializeObject
的参数)
但是,如果您的属性在一个类中,并且您序列化了该类的一个实例,那么它将像您所拥有的一样正常工作,因为它将看到属性上的属性,并知道要使用哪个
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));
}
公共类测试{
[JsonConverter(类型(字典JsonConverter))]
公共字典知识服务器{get;set;}
}
...
静态void Main(字符串[]参数){
测试=新测试(){
KnownServers=新字典(){
{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},
}
};
//这将正确使用Known服务器的DictionaryJsonConverter
WriteLine(JsonConvert.SerializeObject(test));
}
但是,此方法可能不是您想要的,因为它显然也会围绕属性序列化
Test
对象。请创建一个可复制的示例。请参阅。@DavidL添加的示例当编译器为.Net 5时,此代码将在DNF中编译anr un-可以将转换器添加到DefaultSerializationOptions
执行写操作(在本例中)以及反序列化时的读操作。但为什么有必要呢?