tags: 學習記錄 C#

序列化

序列化程序會將物件轉換成位元組資料流,以將物件儲存或傳輸到記憶體、資料庫或檔案。 其主要目的是儲存物件的狀態,這樣就能在需要時重新建立該物件。 反向的程序則稱為還原序列化。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

圖片來源: 微軟文件

The object is serialized to a stream that carries the data. The stream may also have information about the object's type, such as its version, culture, and assembly name. From that stream, the object can be stored in a database, a file, or memory.

序列化的用法

序列化可讓開發人員儲存物件的狀態,並視需要重新建立物件,以提供物件和資料交換的儲存體。 透過序列化,開發人員可以執行下列動作:

  • 使用 web 服務將物件傳送到遠端應用程式
  • 將某個網域的物件傳遞給另一個網域
  • 透過防火牆將物件傳遞為 JSON 或 XML 字串
  • 維護應用程式之間的安全性或使用者特定資訊

JSON 序列化

System.Text.Json命名空間包含 JavaScript 物件標記法 (JSON) 序列化和還原序列化的類別。 JSON 是一種開放式標準,通常用於在網路上共用資料。

用內建的: using System.Text.Json;

序列化

string json = JsonSerializer.Serialize(要序列化的物件);

反序列化

還原的物件 = JsonSerializer.Deserialize<還原的物件>(序列化的字串);

用第三方套件

二進位與 XML 序列化

System.Runtime.Serialization命名空間包含二進位和 XML 序列化和還原序列化的類別。

二進位序列化使用二進位編碼來產生精簡的序列化,適用於儲存或通訊端型網路資料流。 在二進位序列化中,系統會序列化所有成員 (即使是唯讀的成員),且效能會增強。

BinaryFormatter 類型是危險的, 不建議用於資料處理。 應用程式應該儘快停止使用 BinaryFormatter 參考文件

基本序列化

參考資料: 微軟文件

序列化中遇到的問題

The JSON value could not be converted to System.String

ASP.NET Core 3.1 之後都有類似的錯誤
因為微軟預設用 System.Text.Json 來做序列化的轉換
但 System.Text.Json 不能反序列化非字串的值,例如:int, bool 等等

Unexpected character encountered while parsing value

Could not create an instance of type 小算盤第三階.Operators.IOperator. Type is an interface or abstract class and cannot be instantiated