Go语言json数据的编码解码
package main import ( "encoding/json" "fmt" ) type Product struct { Name string //`json:"name"` ProductID int64 `json:"product_id,string"` NoShow string `json:"-"` // 中划线- 表示不进行序列化 Number int `json:"number,string"` Price float64 `json:"price,string"` Price2 float64 `json:"price2,float64"` Price3 float64 `json:"price3,int"` IsOnSale bool `json:"is_on_sale,string"` IsShow bool `json:"is_show,bool"` Empty string `json:"empty,omitempty"` //omitempty,tag里面加上omitempy,可以在序列化的时候忽略0值或者空值 } func main() { product := Product{ Name: "华为手机", ProductID: 1001, NoShow: "中划线- 表示不进行序列化", Number: 200, Price: 1999.99, Price2: 1899.11, Price3: 1599.99, IsOnSale: false, IsShow: false, Empty: "", } //json编码 jsonEncode, _ := json.Marshal(product) fmt.Println(string(jsonEncode)) //{"Name":"华为手机","product_id":"1001","number":"200","price":"1999.99","price2":1899.11,"price3":1599.99,"is_on_sale":"false","is_show":false} //json解码 var strData = `{"Name":"华为手机","product_id":"1001","NoShow":"中划线- 表示不进行序列化","number":"200","price":"1999.99","price2":1899.11,"price3":1599.99,"is_on_sale":"false","is_show":false,"empty":""}` jsonDecode := &Product{} err := json.Unmarshal([]byte(strData), jsonDecode) fmt.Println(err) //<nil> fmt.Println(jsonDecode) //&{华为手机 1001 200 1999.99 1899.11 1599.99 false false } fmt.Println(*jsonDecode) //{华为手机 1001 200 1999.99 1899.11 1599.99 false false } fmt.Printf("%+v", *jsonDecode) //{Name:华为手机 ProductID:1001 NoShow: Number:200 Price:1999.99 Price2:1899.11 Price3:1599.99 IsOnSale:false IsShow:false Empty:} }
//格式 Tag标签 `json:"字段名,omitempty,-,type类型"`
//Tag,tag就是标签,给结构体的每个字段打上一个标签,标签冒号前是类型,后面是标签名。
//omitempty,tag里面加上omitempy,可以在序列化的时候忽略0值或者空值
//-,中划线- 表示不进行序列化
//type,有些时候在序列化或者反序列化的时候,可能结构体类型和需要的类型不一致,这个时候可以指定,支持string,number和boolean