I had the following struct;
type ConditionState struct {
Label string
value int
}
For a graphql API I wanted to marshal this down to only the Label value. The value is for backend logic and I did not want to expose this information to the frontend; For example
var ConditionStateMint = ConditionState{Label: "MINT", value: 100}
I wanted to marshal to;
"MINT"
So I wrote a custom marshaller by overwriting the MarshalJSON method;
func (c *ConditionState) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("\"%s\"", c.Label)), nil
}
The problem I had was that this method was not getting called.
After furious debugging I found out it was because I was attaching this method to the pointer and not the value. see func (c *ConditionState) MarshalJSON
.
This is because it the ConditionState was getting passed into the json unmarshal function as the value and not as a pointer. Simple remove the reference to attach the method to the value.
func (c ConditionState) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("\"%s\"", c.Label)), nil
}