介紹Golang序列化和反序列化
以下由golang教學專欄來介紹Golang序列化和反序列化,希望對需要的朋友有幫助!
為什麼要序列化和反序列化
我們的資料物件要在網路中傳輸或儲存到文件,就需要對其編碼和解碼動作,目前存在許多編碼格式:json, XML, Gob, Google Protocol Buffer 等, Go 語言當然也支援所有這些編碼格式。
序列化與反序列化定義
序列化 (Serialization)是將物件的狀態資訊轉換為可以儲存或傳輸的形式的過程。在序列化期間,物件將其目前狀態寫入到臨時或持久性儲存區。透過從儲存區讀取物件的狀態,重新建立該對象,則為反序列化
序列化與反序列化規則
Go類型 json 類型
bool booleans
float64 numbers# null
#在解析json 格式資料時,若以interface{} 接收數據,需依照以上規則進行解析。
程式碼示範
反序列化
package main
import ( "encoding/json"
"fmt")
type People struct {
name string `json:"name"` // name,小写不导出
Age int `json:"age"` // age
Gender string `json:"gender"` // gender Lesson
}
type Lesson struct {
Lessons []string `json:"lessons"`
}
func main() {
jsonstr := `{"Age": 18,"name": "Jim" ,"gender": "男","lessons":["English","History"],"Room":201,"n":null,"b":false}` // 反序列化 var people People if err := json.Unmarshal([]byte(jsonstr),&people); err == nil { fmt.Println("struct people:") fmt.Println(people)
} // 反序列化 json 字符串中的一部分 var lessons Lesson if err := json.Unmarshal([]byte(jsonstr),&lessons); err == nil { fmt.Println("struct lesson:") fmt.Println(lessons)
} // 反序列化 json 字符串数组
jsonstr = `["English","History"]`
var str []string
if err := json.Unmarshal([]byte(jsonstr), &str); err == nil { fmt.Println("struct str:") fmt.Println(str)
}
}// 打印结果 struct people:
{ 18 男 {[English History]}}
struct lesson:
{[English History]}
struct str:
[English History]
登入後複製
package main import ( "encoding/json" "fmt") type People struct { name string `json:"name"` // name,小写不导出 Age int `json:"age"` // age Gender string `json:"gender"` // gender Lesson } type Lesson struct { Lessons []string `json:"lessons"` } func main() { jsonstr := `{"Age": 18,"name": "Jim" ,"gender": "男","lessons":["English","History"],"Room":201,"n":null,"b":false}` // 反序列化 var people People if err := json.Unmarshal([]byte(jsonstr),&people); err == nil { fmt.Println("struct people:") fmt.Println(people) } // 反序列化 json 字符串中的一部分 var lessons Lesson if err := json.Unmarshal([]byte(jsonstr),&lessons); err == nil { fmt.Println("struct lesson:") fmt.Println(lessons) } // 反序列化 json 字符串数组 jsonstr = `["English","History"]` var str []string if err := json.Unmarshal([]byte(jsonstr), &str); err == nil { fmt.Println("struct str:") fmt.Println(str) } }// 打印结果 struct people: { 18 男 {[English History]}} struct lesson: {[English History]} struct str: [English History]
反序列化
#序列化
package main
import ( "encoding/json"
"fmt")
type People struct {
name string `json:"name"` // name,小写不导出
Age int `json:"age"` // age,在 json 字符串中叫 age
Gender string `json:"gender"` // gender Lesson
}
type Lesson struct {
Lessons []string `json:"lessons"`
}
func main() {
lesson := Lesson{[]string{"Math","English","Chinese"}}
people := &People{
name: "amy",
Age: 22,
Gender: "female",
Lesson: lesson,
} if b, err := json.Marshal(people); err != nil { fmt.Println("Marshal failed...")
}else { fmt.Println(b) fmt.Println(string(b))
}
} // 打印结果
[123 34 97 103 101 34 58 50 50 44 34 103 101 110 100 101 114 34 58 34 102 101 109 97 108 101 34 44 34 108 101 115 115 111 110 115 34 58 91 34 77 97 116 104 34 44 34 69 110 103 108 105 115 104 34 44 34 67 104 105 110 101 115 101 34 93 125]
{"age":22,"gender":"female","lessons["Math","English","Chinese“}
登入後複製
package main import ( "encoding/json" "fmt") type People struct { name string `json:"name"` // name,小写不导出 Age int `json:"age"` // age,在 json 字符串中叫 age Gender string `json:"gender"` // gender Lesson } type Lesson struct { Lessons []string `json:"lessons"` } func main() { lesson := Lesson{[]string{"Math","English","Chinese"}} people := &People{ name: "amy", Age: 22, Gender: "female", Lesson: lesson, } if b, err := json.Marshal(people); err != nil { fmt.Println("Marshal failed...") }else { fmt.Println(b) fmt.Println(string(b)) } } // 打印结果 [123 34 97 103 101 34 58 50 50 44 34 103 101 110 100 101 114 34 58 34 102 101 109 97 108 101 34 44 34 108 101 115 115 111 110 115 34 58 91 34 77 97 116 104 34 44 34 69 110 103 108 105 115 104 34 44 34 67 104 105 110 101 115 101 34 93 125] {"age":22,"gender":"female","lessons["Math","English","Chinese“}
序列化
#序列化-->傳輸-->反序列化
package main
import ( "fmt"
"encoding/json")
type Student struct {
Name string
Age int
Guake bool
Classes []string
Price float32
}
func (s * Student)ShowStu() { fmt.Println("show Student :") fmt.Println("\tName\t:", s.Name) fmt.Println("\tAge\t:", s.Age) fmt.Println("\tGuake\t:", s.Guake) fmt.Println("\tPrice\t:", s.Price) fmt.Printf("\tClasses\t: ") for _, a := range s.Classes { fmt.Printf("%s ", a)
} fmt.Println("")
}
func main() {
st := &Student { "Xiao Ming", 16, true,
[]string{"Math", "English", "Chinese"}, 9.99,
} fmt.Println("before JSON encoding :")
st.ShowStu()
b, err := json.Marshal(st) if err != nil { fmt.Println("encoding faild")
} else { fmt.Println("encoded data : ") fmt.Println(b) fmt.Println(string(b))
}
ch := make(chan string, 1)
go func(c chan string, str string){
c <- str
}(ch, string(b))
strData := <-ch fmt.Println("--------------------------------")
stb := &Student{}
stb.ShowStu()
err = json.Unmarshal([]byte(strData), &stb) if err != nil { fmt.Println("Unmarshal faild")
} else { fmt.Println("Unmarshal success")
stb.ShowStu()
}
}
登入後複製
package main import ( "fmt" "encoding/json") type Student struct { Name string Age int Guake bool Classes []string Price float32 } func (s * Student)ShowStu() { fmt.Println("show Student :") fmt.Println("\tName\t:", s.Name) fmt.Println("\tAge\t:", s.Age) fmt.Println("\tGuake\t:", s.Guake) fmt.Println("\tPrice\t:", s.Price) fmt.Printf("\tClasses\t: ") for _, a := range s.Classes { fmt.Printf("%s ", a) } fmt.Println("") } func main() { st := &Student { "Xiao Ming", 16, true, []string{"Math", "English", "Chinese"}, 9.99, } fmt.Println("before JSON encoding :") st.ShowStu() b, err := json.Marshal(st) if err != nil { fmt.Println("encoding faild") } else { fmt.Println("encoded data : ") fmt.Println(b) fmt.Println(string(b)) } ch := make(chan string, 1) go func(c chan string, str string){ c <- str }(ch, string(b)) strData := <-ch fmt.Println("--------------------------------") stb := &Student{} stb.ShowStu() err = json.Unmarshal([]byte(strData), &stb) if err != nil { fmt.Println("Unmarshal faild") } else { fmt.Println("Unmarshal success") stb.ShowStu() } }
範例
json 資料編碼和解碼 json 套件提供了Decoder 和Encoder 類型來支援常用json 資料流讀寫。 NewDecoder 和 NewEncoder 函式分別封裝了 io.Reader 和 io.Writer 介面。
package main import ( "encoding/json" "fmt" "os" "strings") type People struct { name string `json:"name"` // name,小写不导出 Age int `json:"age"` // age,在 json 字符串中叫 age Gender string `json:"gender"` // gender Lesson } type Lesson struct { Lessons []string `json:"lessons"` } func main() { jsonStr := `{"Age": 18,"name": "Jim" ,"gender": "男","lessons":["English","History"],"Room":201,"n":null,"b":false}` strR := strings.NewReader(jsonStr) people := &People{} // 用 NewDecoder && Decode 进行解码给定义好的结构体对象 people err := json.NewDecoder(strR).Decode(people) if err != nil { fmt.Println(err) } fmt.Printf("%+v",people) // // 用 NewEncoder && Encode 把保存的 people 结构体对象编码为 json 保存到文件 f, err := os.Create("./people.json") json.NewEncoder(f).Encode(people) }
範例
package main import ( "encoding/json" "fmt" "os" "strings" ) type People struct { name string `json:"name"` // name,小写不导出 Age int `json:"age"` // age,在 json 字符串中叫 age Gender string `json:"gender"` // gender Lesson } type Lesson struct { Lessons []string `json:"lessons"` } func main() { jsonStr := `{"Age": 18,"name": "Jim" ,"gender": "男","lessons":["English","History"],"Room":201,"n":null,"b":false}` strR := strings.NewReader(jsonStr) people := &People{} // 用 NewDecoder && Decode 进行解码给定义好的结构体对象 people err := json.NewDecoder(strR).Decode(people) if err != nil { fmt.Println(err) } fmt.Printf("%+v",people) // // 用 NewEncoder && Encode 把保存的 people 结构体对象编码为 json 保存到文件 f, err := os.Create("./people.json") json.NewEncoder(f).Encode(people) } 示例
##
以上是介紹Golang序列化和反序列化的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

在Go中安全地讀取和寫入檔案至關重要。指南包括:檢查檔案權限使用defer關閉檔案驗證檔案路徑使用上下文逾時遵循這些準則可確保資料的安全性和應用程式的健全性。

如何為Go資料庫連線配置連線池?使用database/sql包中的DB類型建立資料庫連線;設定MaxOpenConns以控制最大並發連線數;設定MaxIdleConns以設定最大空閒連線數;設定ConnMaxLifetime以控制連線的最大生命週期。

GoLang框架與Go框架的差異體現在內部架構與外部特性。 GoLang框架基於Go標準函式庫,擴充其功能,而Go框架由獨立函式庫組成,以實現特定目的。 GoLang框架更靈活,Go框架更容易上手。 GoLang框架在效能上稍有優勢,Go框架的可擴充性更高。案例:gin-gonic(Go框架)用於建立RESTAPI,而Echo(GoLang框架)用於建立Web應用程式。

可以透過使用gjson函式庫或json.Unmarshal函數將JSON資料儲存到MySQL資料庫中。 gjson函式庫提供了方便的方法來解析JSON字段,而json.Unmarshal函數需要一個目標類型指標來解組JSON資料。這兩種方法都需要準備SQL語句和執行插入操作來將資料持久化到資料庫中。

後端學習路徑:從前端轉型到後端的探索之旅作為一名從前端開發轉型的後端初學者,你已經有了nodejs的基礎,...

FindStringSubmatch函數可找出正規表示式匹配的第一個子字串:此函數傳回包含匹配子字串的切片,第一個元素為整個匹配字串,後續元素為各個子字串。程式碼範例:regexp.FindStringSubmatch(text,pattern)傳回符合子字串的切片。實戰案例:可用於匹配電子郵件地址中的域名,例如:email:="user@example.com",pattern:=@([^\s]+)$獲取域名match[1]。

Go框架開發常見問題:框架選擇:取決於應用需求和開發者偏好,如Gin(API)、Echo(可擴展)、Beego(ORM)、Iris(效能)。安裝和使用:使用gomod指令安裝,導入框架並使用。資料庫互動:使用ORM庫,如gorm,建立資料庫連線和操作。身份驗證和授權:使用會話管理和身份驗證中間件,如gin-contrib/sessions。實戰案例:使用Gin框架建立一個簡單的部落格API,提供POST、GET等功能。

Go語言中使用預先定義時區包含下列步驟:匯入"time"套件。透過LoadLocation函數載入特定時區。在建立Time物件、解析時間字串等操作中使用已載入的時區,進行日期和時間轉換。使用不同時區的日期進行比較,以說明預先定義時區功能的應用。
