详解go的json对应结构体里的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对应结构体里的Tag是json的key的名字
u := &User{UserId: 1, UserName: "tony"}
j, _ := json.Marshal(u)
fmt.Println(string(j))
// 输出内容:
// {"user_id":1,"user_name":"tony"}
// 如果在属性中不增加标签说明,则输出:
// {"UserId":1,"UserName":"tony"}
// 可以看到直接用struct的属性名做键值。
// ==其中还有一个bson的声明,这个是用在将数据存储到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))
}


结果:


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

// 值为false,0或者空字符串的ProductID和IsOnSalebool都没有出现在最后的json串里。

  1. 有些时候,我们在序列化或者反序列化的时候,可能结构体类型和需要的类型不一致,这个时候可以指定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:,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

如果有不对的,希望各位大佬批评指正。感激不尽。

你可能感兴趣的:(详解go的json对应结构体里的Tag)