Golang中 json tag 標籤的作用和用法講解
阿新 • • 發佈:2021-07-08
結構體的tag
tag是結構體的元資訊,執行時通過反射機制讀取。結構體的tag一般定義在相應欄位的後面,格式為:
fieldName fieldType `key1:"value1" key2:"value2"`
同一個結構體欄位可以設定多個鍵值對tag,不同的鍵值對之間使用空格分隔。
json tag
預設情況下序列化與反序列化使用的都是結構體的原生欄位名,可以通過給結構體欄位新增json tag來指定序列化後的欄位名。標籤冒號前是型別,後面是標籤名。
例如程式碼:
1 // Product _ 2 type Product struct { 3 Name string`json:"name"` 4 ProductID int64 `json:"-"` // 表示不進行序列化 5 Number int `json:"number"` 6 Price float64 `json:"price"` 7 IsOnSale bool `json:"is_on_sale,string"` 8 } 9 10 // 序列化過後,可以看見 11 {"name":"Xiao mi 6","number":10000,"price":2499,"is_on_sale":"false"}
omitempty,tag裡面加上omitempy,可以在序列化的時候忽略0值或者空值。注意此時在“omitempty”前一定指定一個欄位名,否則“omitempty”將作為欄位名處理。
1 package main 2 3 import ( 4 "encoding/json" 5 "fmt" 6 ) 7 8 // Product _ 9 type Product struct { 10 Name string `json:"name"` 11 ProductID int64 `json:"product_id,omitempty"` 12 Number int `json:"number"` 13 Price float64 `json:"price"` 14 IsOnSale bool`json:"is_on_sale,omitempty"` 15 } 16 17 func main() { 18 p := &Product{} 19 p.Name = "Xiao mi 6" 20 p.IsOnSale = false 21 p.Number = 10000 22 p.Price = 2499.00 23 p.ProductID = 0 24 25 data, _ := json.Marshal(p) 26 fmt.Println(string(data)) 27 } 28 // 結果(省略掉了p.IsOnSale 和 p.ProductID) 29 {"name":"Xiao mi 6","number":10000,"price":2499}
若要在被巢狀結構體整體為空時使其在序列化結果中被忽略,不僅要在被巢狀結構體欄位後加上json:"fileName,omitempty",還要將其改為結構體指標。如:
1 package main 2 3 import ( 4 "encoding/json" 5 "fmt" 6 ) 7 8 type BodyInfo struct { 9 Weight float64 10 Height float64 11 } 12 13 type Student struct { 14 Name string `json:"name"` 15 Age int64 16 *BodyInfo `json:"bodyinfo,omitempty"` 17 } 18 19 func main() { 20 s1 := Student{ 21 Name: "jack", 22 Age: 20, 23 } 24 25 data, _ := json.Marshal(s1) 26 fmt.Println(string(data)) 27 } 28 29 //結果 30 {"name":"jack","Age":20}
type,有些時候,我們在序列化或者反序列化的時候,可能結構體型別和需要的型別不一致,這個時候可以指定,支援string,number和boolean
1 package main 2 3 import ( 4 "encoding/json" 5 "fmt" 6 ) 7 8 // Product _ 9 type Product struct { 10 Name string `json:"name"` 11 ProductID int64 `json:"product_id,string"` 12 Number int `json:"number,string"` 13 Price float64 `json:"price,string"` 14 IsOnSale bool `json:"is_on_sale,string"` 15 } 16 17 func main() { 18 19 var data = `{"name":"Xiao mi 6","product_id":"10","number":"10000","price":"2499","is_on_sale":"true"}` 20 p := &Product{} 21 err := json.Unmarshal([]byte(data), p) 22 fmt.Println(err) 23 fmt.Println(*p) 24 } 25 // 結果 26 <nil> 27 {Xiao mi 6 10 10000 2499 true}
參考文章:
GO--Json tag標籤的作用,json用法講解:https://blog.csdn.net/qq_33679504/article/details/100533703
golang-json使用(json tag):https://blog.csdn.net/somanlee/article/details/106925278