簡體   English   中英

SignalR SendAsync 對象列表調用 ToString 而不是使用我的 jsonserializer?

[英]SignalR SendAsync list of objects calls ToString rather than using my jsonserializer?

我正在嘗試將對象列表發送到我的 signalr 客戶端,但該框架似乎忽略了 json 序列化程序並改為使用ToString方法。 只有當它是List<object>時才會發生這種情況,它可以很好地處理常規的object

一個有點做作的簡化示例:

public abstract class Animal {}
public class Dog : Animal {
    public bool GoodBoy { get; set; }
    public override string ToString() {
        return "hello from dog";
    }
}
public class Cat : Animal {
    public bool Hungry { get; set; } // only cats can be hungry, dont think too much about it
}

// ... class MyHub : Hub { ...

// Input is: type = typeof(Dog) and animals is a list of 1 dog
public void SendChanges(Type type, List<Animal> animals) {
    // Just serializing the animals without casting them gives incorrect objects
    Console.WriteLine(JsonSerializer.Serialize(animals)); // Prints [{}]

    // So we have to cast to the input type
    var animalsAsType = animals.Select(a => Convert.ChangeType(a, type).ToList();
    Console.WriteLine(JsonSerializer.Serialize(animalsAsType)); // Prints [{"GoodBoy":true}]

    // However, ...
    Clients.Others.SendAsync($"On{type.Name}Changed", animalsAsType); // Clients receive ["hello from dog"]
}

我在這里做錯了什么? 我懷疑我的 linq Select有問題,但我不確定如何將Animal強制轉換為不使用Convert.ChangeTypetype (如果動物實例實際上不是我們要強制轉換的類型,它會拋出ClassCastException )。 Convert.ChangeType

注意:由於我的真實代碼中的技術限制,我確實要求SendChanges(Type type, List<Animal> animals)的簽名不會改變。

您是否嘗試過將其作為通用方法,而不是將類型作為參數傳遞? 然后它知道運行時的實際類型,因此您不必強制轉換任何內容:

public void SendChanges<T>(List<T> updatedModels)
{
    Clients.Others.SendAsync($"On{typeof(T).Name}Changed", updatedModels);
}

甚至會讓你的 class 有點通用。 如果您想將其限制為動物,只需將where T: Animal添加到方法簽名中即可。

編輯:像這樣使用它:

var cats = new List<Cat>() { new Cat() };
signalerService.SendChanges(cats);

我發現了問題:原來我忘記了我已經注冊了一個使用ToString的自定義 json 轉換器。 一旦我遵循了這個解決方案,一切都完美無缺。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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