如上面的代码所示,可以使用json:",omitempty"省略结构中的某些字段以显示在json中.
例如
type ColorGroup struct {
ID int `json:",omitempty"`
Name string
Colors []string
}
type Total struct {
A ColorGroup`json:",omitempty"`
B string`json:",omitempty"`
}
group := Total{
A: ColorGroup{},
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,B将不会出现json.Marshal(group)
但是,如果
group := Total{
B:"abc",
}
Run Code Online (Sandbox Code Playgroud)
A 仍然出现在 json.Marshal(group)
{"A":{"Name":"","Colors":null},"B":"abc"}
Run Code Online (Sandbox Code Playgroud)
问题是我们如何才得到
{"B":"abc"}
Run Code Online (Sandbox Code Playgroud)
编辑:经过一些谷歌搜索,这里是一个建议使用指针,换句话说,Total变成
type Total struct {
A *ColorGroup`json:",omitempty"`
B string`json:",omitempty"`
}
Run Code Online (Sandbox Code Playgroud)
Ami*_*pta 30
从文档:
结构值编码为JSON对象.每个导出的struct字段都成为对象的成员,除非
- 字段的标记是" - ",或
- 该字段为空,其标签指定"omitempty"选项.
空值为false,0,任何nil指针或接口值,以及长度为零的任何数组,切片,映射或字符串.
在你的声明中group,隐含group.A的是ColorGroupstruct类型的零值.并注意到,在被认为是"空值"的事物列表中没有提到零值结构类型.
正如您所发现的,您的案例的解决方法是使用指针.如果您未A在声明中指定,这将有效group.如果将其指定为指向零结构的指针,则它将再次显示.
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
type colorGroup struct {
ID int `json:",omitempty"`
Name string
Colors []string
}
type total struct {
A *colorGroup `json:",omitempty"`
B string `json:",omitempty"`
}
groupWithNilA := total{
B: "abc",
}
b, err := json.Marshal(groupWithNilA)
if err != nil {
fmt.Println("error:", err)
}
os.Stderr.Write(b)
println()
groupWithPointerToZeroA := total{
A: &colorGroup{},
B: "abc",
}
b, err = json.Marshal(groupWithPointerToZeroA)
if err != nil {
fmt.Println("error:", err)
}
os.Stderr.Write(b)
}
Run Code Online (Sandbox Code Playgroud)