json标签

1 篇文章 0 订阅
1 篇文章 0 订阅

json标签

  • json:"-" // 表示不进行序列化,忽略

  • json:"name,omitempty"//加上omitempty,可以在序列化的时候忽略0值或者空值;若要在被嵌套结构体整体为空时使其在序列化结果中被忽略,不仅要在被嵌套结构体字段后加json:“name,omitempty”,还要将其改为结构体指针

  • json:",inline"通常作用于内嵌的结构体类型type

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    type T1 struct {
        FieldInt     int    `json:"field_int"`
        FieldIgnore  int    `json:"-"`                       //忽略
        FieldBooleab bool   `json:"field_boolean,string"`    //不同类型
        FieldString1 string `json:"field_string1,omitempty"` //忽略空值,当时复合结构时为要为指针类型
        FieldString2 string `json:"field_string2,omitempty"`
    }
    type T2 struct {
        T1 `json:",inline"`  //表示内嵌与T1输出一致
    }
    
    func main() {
        val1 := T1{
            FieldInt:     11,
            FieldIgnore:  11,
            FieldBooleab: true,
            FieldString2: "no empty",
        }
        bty1, _ := json.Marshal(val1)
        fmt.Printf("%v\r\n", string(bty1))
    
        val2 := T2{
            val1,
        }
        bty2, _ := json.Marshal(val2)
        fmt.Printf("%v\r\n", string(bty2))
    }
    
    // output
    // {"field_int":11,"field_boolean":"true","field_string2":"no empty"}
    // {"field_int":11,"field_boolean":"true","field_string2":"no empty"}
    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值