Golang - json omitempty的用法

omitempty的作用是在json数据结构转换时,当该字段的值为该字段类型的零值时,忽略该字段。

package main

import (
    "fmt"
    "encoding/json"
)


type Student struct {
    Name string `json:"name"`
    Age int  `json:"age"`
    Grade  string `json:"grade,omitempty"`
}

func main() {
    stu1 := Student{
        Name:"Tom",
        Age:18,
        Grade:"middle school",
    }

    stu2  := Student{
        Name:"LiLy",
        Age:19,
    }
    stuByts1,_ := json.Marshal(&stu1)
    stuByts2 ,_ := json.Marshal(&stu2)
    fmt.Println("stu1:",string(stuByts1))
    fmt.Println("stu2:",string(stuByts2))
}
打印结果如下:
stu1: {"name":"Tom","age":18,"grade":"middle school"}
stu2: {"name":"LiLy","age":19}  // grade为"",没有解析出来
posted @ 2024-11-29 11:04  李若盛开  阅读(18)  评论(0编辑  收藏  举报