Closed
Description
I discovered this as a breaking change in gin during the time when jsoniter was made the default JSON renderer. I have a struct that looks something like this:
type GeoLocation struct {
Id string `json:"id,omitempty" db:"id"`
Latitude null.Float `json:"latitude" db:"latitude"`
Longitude null.Float `json:"longitude" db:"longitude"`
CreateTime null.Int `json:"createTime" db:"-"`
Created util.NullableTime `json:"-" db:"created"`
Received util.NullableTime `json:"-" db:"received"`
}
And a custom marshaller defined on the pointer of this type:
func (p *GeoLocation) MarshalJSON() ([]byte, error) {
var created string
var received string
if p.Created.Valid {
created = p.Created.Time.Format("2006-01-02 15:04:05")
p.CreateTime.SetValid(p.Created.Time.Unix())
}
if p.Received.Valid {
received = p.Received.Time.Format("2006-01-02 15:04:05")
}
type GeoLocationJSON GeoLocation
return json.Marshal(&struct {
*GeoLocationJSON
CreateTime string `json:"created"`
ReceivedTime string `json:"received"`
}{
CreateTime: created,
ReceivedTime: received,
GeoLocationJSON: (*GeoLocationJSON)(p),
})
}
When rendering a gin response with a slice of these objects, such as:
var locations []GeoLocation
locations = getLocations()
c.JSON(200, locations)
The custom marshaller is not invoked. Changing the marshaller signature to use a value receiver (ie, func (p GeoLocation) MarshalJSON() ([]byte, error)
) does work.
The stdlib version of json handles this as expected.
Metadata
Metadata
Assignees
Labels
No labels