使用结构体嵌套后如何写被嵌套的结构体tags

在学习的过程中突然有一个需求

type A struct{
    UserID uint
    Name string
}

type B struct{
    A
    ...
}

此时我希望有个 tagB 结构体中将 A 结构的 UserID成员在输出json时忽略
当然我有其他办法,比如获取数据后删除
但这个问题我是希望能在结构体中解决
我尝试覆盖,代码如下

type A struct{
    UserID uint
    Name string
}

type B struct{
    A
    UserID uint `json:"-"`
    ...
}

以上写法是无效的,望指点。

嘉宝君
最佳答案

@嘉宝君 B加个UserID不赋值,json使用omitempty忽略0值

type A struct {
    UserID uint
    Name   string
}

type B struct {
    A
    UserID uint `json:",omitempty"`
}
1年前 评论
嘉宝君 (楼主) 1年前
讨论数量: 4

@嘉宝君 B加个UserID不赋值,json使用omitempty忽略0值

type A struct {
    UserID uint
    Name   string
}

type B struct {
    A
    UserID uint `json:",omitempty"`
}
1年前 评论
嘉宝君 (楼主) 1年前

实现Marshaler?

type B struct{
    A
    Age uint
}

func (b B) MarshalJSON()( []byte, error){
    withoutA:=struct{
        Age uint
    }{
        Age: b.Age,
    }
    return json.Marshal(withoutA)
}
1年前 评论
嘉宝君 (楼主) 1年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!