With the given code below, it seems like the custom MarshalJSON
function isn't being called with i hit the api endpoint. Should it be?
type User struct {
FirstName string `json:"first"`
LastName string `json:"last"`
Fullname string `json:"full"`
}
func (u *User) MarshalJSON() ([]byte, error) {
type Alias User
return json.Marshal(&struct {
FullName string `json:"full"`
*Alias
}{
FullName: fmt.Sprintf("%s %s", u.FirstName, u.LastName),
Alias: (*Alias)(u),
})
}
......
user := User{
FirstName: "Bob",
LastName: "Denver",
}
c.JSON(200, user)
I am not seeing the full name attribute filed out like i'd expect. Any thoughts on what i may be missing here?
Comment From: cbarraford
I've been able to limit the issue to be something outside of gin
, so closing ticket.
Comment From: mjip
What was the fix you ended up finding?
Comment From: cbarraford
sorry i don't remember
Comment From: DDevine
The issue seems to be satisfying the interface on *User
rather than User
. Notice the small difference.
Try something like this:
func (u User) MarshalJSON() ([]byte, error) {
type Alias User
return json.Marshal(&struct {
FullName string `json:"full"`
*Alias
}{
FullName: fmt.Sprintf("%s %s", u.FirstName, u.LastName),
Alias: (*Alias)(&u),
})
}
I'm very new to Go, so if this is not helpful for some reason please let me know because I don't want to mislead anybody. Having said that - I've tried it and it works for me!
Comment From: archiewx
@DDevine nice! When using the *User
, only ptr can be called.
Comment From: YannikHinteregger
Omg, thanks! Finding this took me 2 days.