Unmarshal/Marshal json with int set to 0 does not seem to work

Use a pointer for the fields, so that the zero value of the JSON type can be differentiated from the missing value.

type Test struct {
    String  *string `json:"string,omitempty"`
    Integer *int    `json:"integer,omitempty"`
}

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


as the docs says in https://golang.org/pkg/encoding/json/#Marshal

Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless

  • the field's tag is "-", or
  • the field is empty and its tag specifies the "omitempty" option. The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object's default key string is the struct field name but can be specified in the struct field's tag value. The "json" key in the struct field's tag value is the key name, followed by an optional comma and options.

so no, unless you implement your own marshaller for your struct


"omitempty" tag makes sense only for marshaling from struct to JSON. It skips empty values so they won't be in JSON. It doesn't affect unmarshaling in any way. Use pointers if you want to detect whether the field is specified in JSON or not. If the field is not specified, the pointer value will be nil.

Tags:

Json

Go