Go语言中的`json.Marshal()`函数在处理字节数组字段时忽略了`omitempty`选项。

huangapple go评论63阅读模式
英文:

Go lang json.Marshall() ignores omitempty in ByteArray Fields

问题

请参考以下内容。

https://play.golang.org/p/HXrqLqYIgz

我的期望值是:

{"Byte2":0,"Name":"bob"}

但实际结果是:

{"ByteArray":[0,0,0,0],"Byte2":0,"Name":"bob"}

根据文档(https://golang.org/pkg/encoding/json/)

空值包括 false、0、任何 nil 指针或接口值,以及长度为零的数组、切片、映射或字符串。

因此,json.Marshall() 忽略了 omitempty 标签,因为 [0 0 0 0] 不是零长度、0 或 nil。

现在,为了得到期望的值,我们应该怎么做?

英文:

Please see below.

https://play.golang.org/p/HXrqLqYIgz

My expected value is:

{"Byte2":0,"Name":"bob"}

But Actual:

{"ByteArray":[0,0,0,0],"Byte2":0,"Name":"bob"}

According to the document (https://golang.org/pkg/encoding/json/)

> The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero.

Therefore, json.Marshall() ignores omitempty-tag, because [0 0 0 0] is not zero-length nor 0 nor nil.

And now, to get the expected value, What should we do?

答案1

得分: 4

几个选项:

  1. A作为一个具有自己的MarshalJSON方法的类型的实例,并在其中实现所需的行为(例如,如果ByteArray的所有值都为零,则不包括它)。

  2. 更改ByteArray的类型。[]byte 可以工作,因为它默认为一个空切片,*[4]byte也可以工作,因为它默认为nil。包含一个指针是处理只在序列化中有时出现的字段的常见方法。当然,这需要一点更多的空间、一点更多的间接引用和一点更多的垃圾回收工作。

英文:

A few options:

  1. Make A an instance of a type with its own MarshalJSON method and implement the behavior you want there (e.g. not including ByteArray if all of its values are zero).

  2. Change the type of ByteArray. []byte would work since it defaults to an empty slice, and *[4]byte would work since it defaults to nil. Including a pointer is a common way of dealing with a field that's only sometimes present in serialization. Of course this does require a little more space, a little more indirection, and a little more GC work.

答案2

得分: 1

你需要将ByteArray要么改为切片,要么改为数组指针:

type A struct {
	ByteArray []*byte `json:",omitempty"`
	Byte1     byte    `json:",omitempty"`
	Byte2     byte
	Name      string  `json:",omitempty"`
}

Playground: https://play.golang.org/p/nYBqGrSA1L.

英文:

You'll have to either make ByteArray a slice, or a pointer to array:

type A struct {
	ByteArray *[4]byte `json:",omitempty"`
	Byte1     byte     `json:",omitempty"`
	Byte2     byte
	Name      string `json:",omitempty"`
}

Playground: https://play.golang.org/p/nYBqGrSA1L.

huangapple
  • 本文由 发表于 2015年12月2日 00:19:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/34024992.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定