Carefully implemented json.Marshaler and json.Unmarshaler interfaces, and passed my struct directly to json.Marshal().
What did you expect to see?
The resulting JSON byte array uses my custom json.Marshaler interface method.
What did you see instead?
The resulting JSON byte array ignores my custom json.Marshaler interface method, instead presenting the keys and values of the plain Go struct declaration. This causes downstream breakages, as my custom JSON marshaling is needed to offset some issues with the data I happen to be handling.
As a workaround, I am making sure that I pass a reference (&) of my object to the json.Marshal() method. This is quite dangerous, as it is a really easy mistake to make, across a large codebase. And currently no way to validate this with the Go type system on the existing API. With other Go API calls, I at least get an annoying compile about needing a receiver pointer.
In the future, can we improve the json API to prevent this from happening?
The text was updated successfully, but these errors were encountered:
If at all possible, please include in the "what did you do" section the actual code, and in the "what did you see instead" the actual result and errors if any. This would make it so much easier to analyze and help.
My guess is that the value you pass to json.Marshal(yourval) does not actually implement the json.Marshal interface at all, probably because the method had a pointer receiver e.g., func (x *MyType) MarshalJSON() (byte, error and you passed a MyType value, not a pointer.