Go lang json.Marshall()忽略ByteArray字段中的遗弃

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?

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.

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.