go - 如何有选择地编码(marshal)结构的 JSON?

标签 go

我有一个结构:

type Paper struct {
    PID    int    `json:"pID"`
    PTitle string `json:"pTitle"`
    PDesc  string `json:"pDesc"`
    PPwd   string `json:"pPwd"`
}

大多数情况下,我会将整个结构编码为 JSON。然而,偶尔,我需要 结构的简短版本;即编码一些属性,我应该如何实现这个功能?

type BriefPaper struct {
    PID    int    `json:"-"`      // not needed
    PTitle string `json:"pTitle"`
    PDesc  string `json:"pDesc"`
    PPwd   string `json:"-"`      // not needed
}

我正在考虑创建一个子集结构,类似于 BriefPaper = SUBSET(Paper),但不确定如何在 Golang 中实现它。

我希望我能做这样的事情:

p := Paper{ /* ... */ }
pBrief := BriefPaper{}

pBrief = p;
p.MarshalJSON(); // if need full JSON, then marshal Paper
pBrief.MarshalJSON(); // else, only encode some of the required properties

这可能吗?

最佳答案

可能最简单的方法是创建一个嵌入 Paper 的结构,并隐藏要隐藏的字段:

type Paper struct {
    PID    int    `json:"pID"`
    PTitle string `json:"pTitle"`
    PDesc  string `json:"pDesc"`
    PPwd   string `json:"pPwd"`
}

type BriefPaper struct {
    Paper
    PID    int    `json:"pID,omitempty"`  // Just make sure you 
    PPwd   string `json:"pPwd,omitempty"` // don't set these fields!
}

p := Paper{ /* ... */ }
pBrief := BriefPaper{Paper: p}

现在,当编码 BriefPaper 时,字段 PIDPPwd 将被省略。

关于go - 如何有选择地编码(marshal)结构的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56982842/

相关文章:

docker - 无法连接到 Docker 容器中的 Go Server

http - groupcache 的 peers 之间的通信

go - 使用结构字段中的类型进行类型断言

linux - 无法输出缓冲区

linux - 无法从 git clone go.googlesource.com 克隆 Git 存储库

go - 服务器端 oauth : What to do with the tokens received

json - 出现错误 : math/big: cannot unmarshal into a *big. Int

reflection - 如何反射(reflect)Golang中对象的动态方法名

去隐式转换接口(interface)做内存分配?

arrays - 我在 golang 中使用 make 方法创建二维数组时遇到问题 "panic: runtime error: index out of range"