13

【答客問】NSwag WebAPI 回傳 DataTable 發生 JSON property 'Item' is defined multi...

 3 years ago
source link: https://blog.darkthread.net/blog/nswag-return-datatable/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
【答客問】NSwag WebAPI 回傳 DataTable 發生 JSON property 'Item' is defined multiple times 錯誤-黑暗執行緒

讀者 Bike 提到「NSwag 遇到回傳 DataTable 的 Action 會回傳 The JSON property 'Item' is defined multiple times on type 'System.ComponentModel.ComponentCollection' 錯誤」的問題。

同樣問題我也遇過,用 NSwag + WebAPI 回傳 DataTable 型別,大概只會發生在古蹟維修改建時,有現化與傳統融合的趣味,但 NSwag 遇到回傳 DataTable 會在 JSON 序列化時出錯。NSwag Github Issue 區有相關討論,結論是 Request/Response 遇到 Model 屬性型別繼承自 System.ComponentModel 會出現 The JSON property 'Item' is defined multiple times on type 錯誤。除了 DataTable,有其他開發者在使用 KeyedCollection、JArray 時也踩到相同問題。

在專案遇到這個問題,身為老司機,加上對 WebAPI 介面規格沒什麼堅定信仰,我選擇輕打方向盤,繞過石頭繼續前進。以下是我的 Workaround,定義一個 DataTableBox 類別取代 DataTable:

public class DataTableBox
{
    public string DataTableJson { get; set; }

    public DataTable GetDataTable() => JsonConvert.DeserializeObject<DataTable>(DataTableJson);

    public DataTableBox(DataTable table)
    {
        DataTableJson = JsonConvert.SerializeObject(table);
    }
    public DataTableBox()
    {

    }
}

將 Action 回傳資料型別由 DataTable 改成 DataTableBox。用 new DataTableBox(dataTableObject) 將 DataTable 轉成 DataTableBox,接收端則呼叫 .GetDataTable() 取回 DataTable,多寫幾行 Code 輕巧避開 NSwag 問題。


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK