Documentation ¶
Overview ¶
This example explores exhaustively the behaviour of encoding/json when handling types that implement marshaler interfaces.
When encoding values, encoding/json makes no distinction between pointer and base types: if the base type implements a marshaler interface, be it with plain receiver or pointer receiver, json.Marshal picks it up.
json.Marshaler is always preferred to encoding.TextMarshaler, without any consideration for the receiver type.
When encoding map keys, on the other hand, the map key type must implement encoding.TextMarshaler strictly, i.e. if the interface is implemented only for plain receivers, pointer keys will not be accepted.
json.Marshaler is ignored in this case, i.e. it makes no difference whether the key type implements it or not.
Decoding behaviour w.r.t. unmarshaler types mirrors encoding behaviour.