decimal
decimal copied to clipboard
Json tag omitempty does not work for decimal
Although there is omitempty tag decoration in decimal type, and the value is 0 or not fetched from table, but the result is always "0". I checked the source code, it does not consider the tag of Json and omitempty when MarshalJSON, see below:
func (d Decimal) MarshalJSON() ([]byte, error) {
var str string
if MarshalJSONWithoutQuotes {
str = d.String()
} else {
str = "\"" + d.String() + "\""
}
return []byte(str), nil
}
Is it a problem? thanks! :)
The type Decimal
though acts and sounds like an int/float, but is actually a struct
. This means encoding/json won't omit it unless you make the field a pointer and send nil
into it.
The isEmptyValue() in line 750 returns true
(required to omit) only if field is a pointer to struct and a nil
is sent as value.
struct {
Number *decimal.Decimal `json:"number,omitempty"`
}{
Number: nil,
}
Control reaches MarshalJSON
only when isEmptyValue() == false
, i.e., encoding/json
is not omitting the field. Controlling the behavior in MarshalJSON
won't help.
@vaguecoder I found your comment really helpful. I was running into the same thing with xml. Using a *decimal.Decimal
solved my issue. A really excellent explanation here. Thanks.
@vaguecoder I found your comment really helpful. I was running into the same thing with xml. Using a
*decimal.Decimal
solved my issue. A really excellent explanation here. Thanks.
@mk-j I'm glad. Thanks for letting me know. 😊