序列化與反序列化

2021-10-02 09:27:11 字數 2584 閱讀 8547

具體操作:

序列化為json檔案

總結:將物件(如person物件)轉換為二進位制資料(位元組流)

其實最終儲存在了檔案中,檔案是一種流的源頭(後備儲存),檔案流就是流向檔案的通道(介質)

將二進位制資料還原為物件

從檔案中通過二進位製流,將物件還原出來

在於應用場景不同,資料庫儲存是為了物件持久化,將物件儲存在資料庫檔案中。而序列化按照特定格式將物件儲存在檔案中,保證了物件持久化之後,更側重於網路傳輸,比如json檔案。

1.要序列化的student類

[

serializable

]//標識為可序列化

class

student

set}

private

int age;

public

int age

set}

}

2.引入命名空間
using system.runtime.serialization.formatters.binary;

using system.io;

3.序列化**

序列化student物件到student.txt檔案中

static

void

main

(string

args)

;//建立流

using

(filestream fs =file.

create

("student.txt"))

console.

read()

;}

4.驗證結果

在該程式的debug中建立乙個student.txt檔案

5.反序列化

將student物件從student.txt檔案中還原出來

static

void

main

(string

args)

console.

read()

;}

6.顯示結果:

1.要序列化的student類

這次加入了乙個show方法,在反序列化為物件時呼叫,驗證反序列化成功

[

datacontract

]//要標識

public

class

student

set}

[datamember

(name =

"age")]

//要標識

private

int age;

public

int age

set}

public

void

show()

",name);}

}

2.引入命名空間

在student類中引入

using system.runtime.serialization;
在序列化類(自定義乙個類,下面會有)中引入

using system.runtime.serialization.json;

using system.io;

3.定義乙個序列化類
public

class

endserialize

//反序列化

public

student

deserialize

(string jsonstr)

}

4.外部呼叫
static

void

main

(string

args)

;endserialize ser =

newendserialize()

;//序列化student物件為json字串

string stustr= ser.

serializel

(s);

console.

writeline

(stustr)

;//從json字串中提取物件

student s1= ser.

deserialize

(stustr)

;//物件呼叫自身方法

s1.show()

; console.

read()

;}

5.驗證結果:

序列化與檔案流相關,序列化物件後通過流儲存到檔案中

反序列化開啟檔案形成流,還原成物件

序列化和反序列化 C 序列化與反序列化。

序列化介紹 把物件用一種新的格式來表示。系列化只序列化資料。序列化不建議使用自動屬性 為什麼要序列化 將乙個複雜的物件轉換流,方便儲存與資訊交換。class program class person public int age 二進位制序列化 就是將物件變成流的過程,把物件變成byte class...

序列化與反序列化

把複雜的資料型別壓縮到乙個字串中 serialize 把變數和它們的值編碼成文字形式 unserialize 恢復原先變數 eg stooges array moe larry curly new serialize stooges print r new echo print r unserial...

序列化與反序列化

序列化是將物件處理為位元組流以儲存物件或傳輸到記憶體 資料庫或檔案。其主要目的是儲存物件的狀態,以便可以在需要時重新建立物件。相反的過程稱為反序列化。通過序列化,開發人員可以儲存物件的狀態,並在需要時重新建立該物件,從而提供物件的儲存以及資料交換。通過序列化,開發人員還可以執行類似如下的操作 通過 ...