2

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?

  • Related: http://stackoverflow.com/questions/18088294/how-to-not-marshal-an-empty-struct-into-json-with-go – hobbs Dec 01 '15 at 16:27
  • It cannot omit an byte array: It's a value type and there always present with it's default value. – 0x434D53 Dec 01 '15 at 17:38

2 Answers2

4

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.

hobbs
  • 223,387
  • 19
  • 210
  • 288
1

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.

Ainar-G
  • 34,563
  • 13
  • 93
  • 119