目录
- 前言
 - 序列化
 - array、slice、map、struct对象
 - 序列化的接口
 - 反序列化
 - slice、map、struct反序列化
 - 总结
 
前言
Go语言的序列化与反序列化在工作中十分常用,在Go语言中提供了相关的解析方法去解析JSON,操作也比较简单
序列化
// 数据序列化
func Serialize(v interface{})([]byte, error)
// fix参数用于添加前缀
//idt参数用于指定你想要缩进的方式
func serialization (v interface{}, fix, idt string) ([]byte, error)
array、slice、map、struct对象
//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中,我们会先去检测传进来对象是否为内置类型,是则编码,不是则会先检查当前对象是否已经实现了Marshaler接口,实现则执行MarshalJSON方法得到自定义序列化后的数据,没有则继续检查是否实现了TextMarshaler接口,实现的话则执行MarshalText方法对数据进行序列化
MarshalJSON与MarshalText方法虽然返回的都是字符串,不过MarshalJSON方法返回的带引号,MarshalText方法返回的不带引号
//返回带引号字符串
type Marshaler interface {
    MarshalJSON() ([]byte, error) 
}
type Unmarshaler interface {
	UnmarshalJSON([]byte) error
}
//返回不带引号的字符串
type TextMarshaler interface {
    MarshalText() (text []byte, err error) 
}
type TextUnmarshaler interface {
	UnmarshalText(text []byte) error
}
反序列化
func Unmarshal(data [] byte, arbitrarily interface{}) error
该函数会把传入的数据作为json解析,然后把解析完的数据存在arbitrarily中,arbitrarily是任意类型的参数,我们在用此函数进行解析时,并不知道传入参数类型所以它可以接收所有类型且它一定是一个类型的指针
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)
}
总结
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
		
评论(0)