【语言知识】golang struct tag type -- json

本文介绍了Golang中struct在进行json marshal/unmarshal时,如何使用tag type来控制字段转换规则。特别是`inline`、`omitempty`和`-`的用法。`inline`常用于内嵌结构体,`omitempty`会忽略值为空的字段,`-`则会完全忽略指定字段,即使其有值也不会出现在json输出中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

json tag type

  • json tag type用于struct marshal/unmarshal时,将结构体字段按照一定规则,转换为json字段,如下文,Project结构体,marshal后"Name"转换为"name"
    type Project struct {
    	Name string `json:"name"`
    	Id string  `json:"id"`
    }
    
  • 基本格式: Name(定义的字段名) string(类型) json:"opt1,opt2" key:"value"

tag:inline

  • 常用语内嵌结构体
  • 未定义inline时,如下输出:
    type Project struct {
    	Name string `json:"name"`
    	Id string  `json:"id"`
    }
    
    type ProjectList struct {
    	Project `json:"project"`
    	Description string `json:"description"`
    }
    
    func main() {
    	p := Project{
    		Name: "projectA",
    		Id: "xxx01",
    	}
    	pL := ProjectList{
    		p,
    		"Has one Project",
    	}
    	body, _ := json.Marshal(pL)
    	fmt.Printf("marshal body is: %v\n", string(body))
    	}
    
    输出:
    D:\restfulAPIPractise>go run main.go
    marshal body is: {"project":{"name":"projectA","id":"xxx01"},"description":"Has one Project"}
    
  • 定义json:",inline"时:
    如将上文做一下变更:
    type ProjectList struct {
    	Project `json:",inline"`   // 变更点
    	Description string `json:"description"`
    }
    
    输出:
    D:\restfulAPIPractise>go run main.go
    marshal body is: {"name":"projectA","id":"xxx01","description":"Has one Project"}
    

type:omitempty

  • omitempty,当字段值为空时,忽略
    type ProjectList struct {
    	Project `json:"project"`
    	Description string `json:"description,omitempty"`   // omitempty
    }
    
    输出,description为空值,输出不显示:
    marshal body is: {"project":{"name":"projectA","id":"xxx01"}}
    
  • 对比,当不设置omitempty时
    type ProjectList struct {
    	Project `json:"project"`
    	Description string `json:"description"` // 未设置omitempty
    }
    
    输出:
    marshal body is: {"project":{"name":"projectA","id":"xxx01"},"description":""}
    

tag: -

  • json:“-”,忽略,即便字段有值
    type ProjectList struct {
    	Project `json:"project"`
    	Description string `json:"-"`    //
    }
    // main中
    pL := ProjectList{
    	p,
    	"xxx happy",   // description有值
    }
    
    输出:
    marshal body is: {"project":{"name":"projectA","id":"xxx01"}}
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值