#`json.Unmarshal` ignoring `UnmarshalText`

18 messages · Page 1 of 1 (latest)

dawn stump
small matrix
#

i don’t quite follow, it seems like it’s being used here?

#

you’re getting a time parsing error

dawn stump
#

You can also drop an fmt.Println("here") inside UnmarshalText and it won't get called

small matrix
#

ah, time.Time has an UnmarshalJSON and you’re embedding it, so that takes precedence

regal cedar
dawn stump
small matrix
#

two separate things you’re dealing with: the order in which encoding/json tries methods, and the fact that defining a method on a type hides the same method on an embedded type

#

for the first, quoting encoding/json docs:

To unmarshal JSON into a value implementing Unmarshaler, Unmarshal calls that value's [Unmarshaler.UnmarshalJSON] method, including when the input is a JSON null. Otherwise, if the value implements encoding.TextUnmarshaler and the input is a JSON quoted string, Unmarshal calls encoding.TextUnmarshaler.UnmarshalText with the unquoted form of the string.

dawn stump
#

Ahhhh now I get it

#

Without my UnmarshalJSON hiding the one from time.Time it ends up using that

small matrix
#

yep, because embedding a type promotes its methods

#

(that’s essentially the point of embedding a type; don’t do it if you don’t want that behavior)

dawn stump
#

eh, it is a little less than ideal but I guess I can just implement UnmarshalJSON and MarshalJSON and handle the quoting myself

dreamy harbor
#

if your inputs are well defined you don't need to do more than ignore the outer quotes (and handle null)
otherwise, Carson already gave you the solution, don't embed

regal cedar
small matrix
#

encoding/json first sees if the type implements json.Unmarshaler. that’s totally separate from embedding concerns