詳解go的json對應(yīng)結(jié)構(gòu)體里的Tag

資料來源:https://www.bookstack.cn/read/gobook/go_lang_base-09.1.3.md, https://www.cnblogs.com/lurenq/p/11533219.html

  1. golang的json對應(yīng)結(jié)構(gòu)體里的Tag是json的key的名字
u := &User{UserId: 1, UserName: "tony"}
j, _ := json.Marshal(u)
fmt.Println(string(j))
// 輸出內(nèi)容:
// {"user_id":1,"user_name":"tony"}
// 如果在屬性中不增加標(biāo)簽說明,則輸出:
// {"UserId":1,"UserName":"tony"}
// 可以看到直接用struct的屬性名做鍵值。
// ==其中還有一個bson的聲明,這個是用在將數(shù)據(jù)存儲到mongodb使用的==

  1. tag里面加上omitempy,可以在序列化的時候忽略0值或者空值
package main

import (
    "encoding/json"
    "fmt"
)

// Product _
type Product struct {
    Name      string  `json:"name"`
    ProductID int64   `json:"product_id,omitempty"`
    Number    int     `json:"number"`
    Price     float64 `json:"price"`
    IsOnSale  bool    `json:"is_on_sale,omitempty"`
    Amount     int     `json:"amount"`
}

func main() {
    p := &Product{}
    p.Name = "Xiao mi 6"
    p.IsOnSale = false
    p.Number = 10000
    p.Price = 2499.00
    p.ProductID = 0
    data, _ := json.Marshal(p)
    fmt.Println(string(data))
}


結(jié)果:


{"name":"Xiao mi 6","number":10000,"price":2499,"amount":0}

// 值為false,0或者空字符串的ProductID和IsOnSalebool都沒有出現(xiàn)在最后的json串里。

  1. 有些時候,我們在序列化或者反序列化的時候,可能結(jié)構(gòu)體類型和需要的類型不一致,這個時候可以指定tag的type支持
package main

import (
    "encoding/json"
    "fmt"
)

// Product _
type Product struct {
    Name      string  `json:"name"`
    ProductID int64   `json:"product_id,string"`
    Number    int     `json:"number,string"`
    Price     float64 `json:"price,string"`
    IsOnSale  bool    `json:"is_on_sale,string"`
}

type ProductV2 struct {
    Name      string  `json:"name"`
    ProductID int64   `json:"product_id"`
    Number    int     `json:"number"`
    Price     float64 `json:"price"`
    IsOnSale  bool    `json:"is_on_sale"`
}

func main() {
    var data = `{"name":"Xiao mi 6","product_id":"10","number":"10000","price":"2499","is_on_sale":"true"}`
    p := &Product{}
    err := json.Unmarshal([]byte(data), p)
    fmt.Printf("[have type] err:%v,p:%+v\n", err, p)

    p2 := &ProductV2{}
    err = json.Unmarshal([]byte(data), p2)
    fmt.Printf("[no type] err:%v,p:%+v\n", err, p2)
}



輸出:

[have type] err:<nil>,p:&{Name:Xiao mi 6 ProductID:10 Number:10000 Price:2499 IsOnSale:true}
[no type] err:json: cannot unmarshal string into Go struct field ProductV2.product_id of type int64,p:&{Name:Xiao mi 6 ProductID:0 Number:0 Price:0 IsOnSale:false}

其中json的type如下:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

如果有不對的,希望各位大佬批評指正。感激不盡。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容