簡體   English   中英

自定義通用 json 轉換器未調用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM