欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Go語(yǔ)言中序列化與反序列化示例詳解

 更新時(shí)間:2022年07月21日 11:04:28   作者:前端若水  
我們的數(shù)據(jù)對(duì)象要在網(wǎng)絡(luò)中傳輸或保存到文件,就需要對(duì)其編碼和解碼動(dòng)作,Go語(yǔ)言當(dāng)然也支持所有這些編碼格式,下面這篇文章主要給大家介紹了關(guān)于Go語(yǔ)言中序列化與反序列化的相關(guān)資料,需要的朋友可以參考下

前言

Go語(yǔ)言的序列化與反序列化在工作中十分常用,在Go語(yǔ)言中提供了相關(guān)的解析方法去解析JSON,操作也比較簡(jiǎn)單

序列化

// 數(shù)據(jù)序列化
func Serialize(v interface{})([]byte, error)

// fix參數(shù)用于添加前綴
//idt參數(shù)用于指定你想要縮進(jìn)的方式
func serialization (v interface{}, fix, idt string) ([]byte, error)

array、slice、map、struct對(duì)象

//struct
import (
	"encoding/json"
	"fmt"
)

type Student struct {
	Id   int64
	Name string
	Desc string
}

 func fn() {
	std := &Student{0, "Ruoshui", "this to Go"}
	data, err := json.MarshalIndent(std, "", "   ")  
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(data))
}
//array、slice、map
func fc() {
	s := []string{"Go", "java", "php"}
	d, _ := json.MarshalIndent(s, "", "\t")
	fmt.Println(string(d))
	
	m := map[string]string{
		"id": "0",
		"name":"ruoshui",
		"des": "this to Go",
	}
	bytes, _ := json.Marshal(m)
	fmt.Println(string(bytes))
}

序列化的接口

在json.Marshal中,我們會(huì)先去檢測(cè)傳進(jìn)來(lái)對(duì)象是否為內(nèi)置類型,是則編碼,不是則會(huì)先檢查當(dāng)前對(duì)象是否已經(jīng)實(shí)現(xiàn)了Marshaler接口,實(shí)現(xiàn)則執(zhí)行MarshalJSON方法得到自定義序列化后的數(shù)據(jù),沒(méi)有則繼續(xù)檢查是否實(shí)現(xiàn)了TextMarshaler接口,實(shí)現(xiàn)的話則執(zhí)行MarshalText方法對(duì)數(shù)據(jù)進(jìn)行序列化

MarshalJSON與MarshalText方法雖然返回的都是字符串,不過(guò)MarshalJSON方法返回的帶引號(hào),MarshalText方法返回的不帶引號(hào)

//返回帶引號(hào)字符串
type Marshaler interface {
    MarshalJSON() ([]byte, error) 
}
type Unmarshaler interface {
	UnmarshalJSON([]byte) error
}

//返回不帶引號(hào)的字符串
type TextMarshaler interface {
    MarshalText() (text []byte, err error) 
}
type TextUnmarshaler interface {
	UnmarshalText(text []byte) error
}

反序列化

func Unmarshal(data [] byte, arbitrarily interface{}) error

該函數(shù)會(huì)把傳入的數(shù)據(jù)作為json解析,然后把解析完的數(shù)據(jù)存在arbitrarily中,arbitrarily是任意類型的參數(shù),我們?cè)谟么撕瘮?shù)進(jìn)行解析時(shí),并不知道傳入?yún)?shù)類型所以它可以接收所有類型且它一定是一個(gè)類型的指針

slice、map、struct反序列化

//struct
type Student struct {
	Id int64    `json:"id,string"`
	Name string `json:"name,omitempty"`
	Desc string `json:"desc"`
}

func fn() {
	str := `{"id":"0", "name":"ruoshui", "desc":"new Std"}`
	var st Student
	_ = json.Unmarshal([]byte(str), &st)
	fmt.Println(st)
}
//slice和map
func f() {
	slice := `["java", "php", "go"]`
	var sli []string
	_ = json.Unmarshal([]byte(slice), &sli)
	fmt.Println(sli)


	mapStr := `{"a":"java", "b":"node", "c":"php"}`
	var newMap map[string]string
	_ = json.Unmarshal([]byte(mapStr), &newMap)
	fmt.Println(newMap)
}

總結(jié)

到此這篇關(guān)于Go語(yǔ)言中序列化與反序列化的文章就介紹到這了,更多相關(guān)Go序列化與反序列化內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論