Go结构体标签

omitempty

作用:表示在转成json的时候,如果该字段没有提供,那么就不显示该值。
例如:给Time添加omitempty,没传入值的时候,转换json不会包含该字段.

type response2 struct {
    
    
	Code int `json:"code"`
	Messgae string `json:"messgae"`
	Time string `json:"time,omitempty"`
}
func main() {
    
    
	// 指定omitempty没传入值 转json就不显示
	res2 := response2{
    
    Code: 200, Messgae: "success"}
	m2, _ := json.Marshal(res2)
	fmt.Println("m2", string(m2))	// m2 {"code":200,"messgae":"success"}
}

注意点:

  1. omitempty如果传入的值是默认空值(例如int传入0),那么会在转json的时候被忽略。我们应该思考,是否该字段需要设置omitempty?
  2. omitempty无法忽略嵌套结构体,除非在内嵌的结构体中每个字段都添加omitempty字段。那么如果内嵌结构体没传入,或者没有有效数值(非理论空值) 那么该结构体就会被忽略。但是这样做,是十分不符合实际的。(之所以无法被忽略,是因为go无法区分怎样的结构体是空的)
  3. 结构体的内嵌结构体,即使指定omitempty没传值也不会被忽略,除了第2点说的情况,但如果引入的是该结构体的指针类型,那么golang知道指针的空置值(nil),就可以成功忽略了。
// omitempty关键字 学习
type response1 struct {
    
    
	Code int `json:"code,omitempty"`
	Messgae string `json:"messgae"`
	Time string `json:"time"`
	Result student1 `json:"return,omitempty"`
}
type student1 struct {
    
    
	Name string `json:"name"`
	Age int `json:"age"`
}
func Struct10() {
    
    
	// 若传入的值是默认空值 则会被忽略 如code是int型 默认空值是0 所以code在json转换的时候会被忽略
	res1 := response1{
    
    0,"success","2022-02-18",student1{
    
    "lena",20}}
	m1, _ := json.Marshal(res1)
	fmt.Println("m1",string(m1))	// {"messgae":"success","time":"2022-02-18","return":{"name":"lena","age":20}}
	// 若是结构体类型 空结构体也不会被忽略 如student1没有传入值 但是json转换的时候还是会显示空的student1 因为Go无法区分结构体如何为空
	res2 := response1{
    
    Code: 200,Messgae: "success",Time: "2022-02-18"}
	m2, _ := json.Marshal(res2)
	fmt.Println("m2",string(m2))	// {"code":200,"messgae":"success","time":"2022-02-18","return":{"name":"","age":0}}
}
type response2 struct {
    
    
	Code int `json:"code,omitempty"`
	Messgae string `json:"messgae"`
	Time string `json:"time,omitempty"`
	Result *student2 `json:"return,omitempty"`
}
type student2 struct {
    
    
	Name string `json:"name,omitempty"`
	Age int `json:"age,omitempty"`
}
func Struct11() {
    
    
	// 结构体内嵌的结构体 改用了指针类型 指针的默认空值是nil 因此如果我们没传入 就不会显示
	res1 := response2{
    
    Code: 200, Messgae: "success", Time: "2022-02-18"}
	m1, _ := json.Marshal(res1)
	fmt.Println("m1", string(m1))	// m1 {"code":200,"messgae":"success","time":"2022-02-18"}

猜你喜欢

转载自blog.csdn.net/lena7/article/details/123000844