【问题标题】:Custom generic json converter not called未调用自定义通用 json 转换器
【发布时间】:2021-01-20 08:54:11
【问题描述】:

我有一个用于字典的自定义 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 中编译)
我不保证读取或写入方法是正确的,因为我从未见过结果。

【问题讨论】:

  • 请创建一个可重现的示例。见minimal reproducible example
  • @DavidL 添加示例
  • 当编译器为 .Net 5 - dotnetfiddle.net/g1yCAF 时,此代码将在 DNF 中编译
  • 好的,将转换器添加到DefaultSerializationOptions 执行写入(在此示例中)并在反序列化时读取。但为什么有必要呢?

标签: c# json.net


【解决方案1】:

我认为问题在于您不能只执行JsonConvert.SerializeObject(SomeDictionaryThatHappensToBeInAProperty),因为那样它就看不到JsonConverterAttribute。它所知道的是,它已经从某个地方获得了一个字典。因此,它将使用它拥有的任何JsonConverter 用于字典。

因此,您需要明确告诉 Json.NET 使用哪个转换器。从您的 cmets 中,您似乎找到了一种方法来告诉 Json.NET 使用哪个转换器(通过将转换器存储在 JsonSerializerSettings 实例的 Converters 属性中并将其作为参数提供给 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));
}

此方法可能不是您想要的,因为它显然也会序列化“围绕”属性的Test 对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    • 2016-11-11
    • 2017-06-22
    相关资源
    最近更新 更多