Does anyone know why json.Unmarshal would ignore my UnmarshalText function here? https://go.dev/play/p/VDuRfIiCpGF
If I implement UnmarshalJSON instead and unquote the string by hand it works fine
#`json.Unmarshal` ignoring `UnmarshalText`
18 messages · Page 1 of 1 (latest)
i don’t quite follow, it seems like it’s being used here?
you’re getting a time parsing error
but note the error, it's not using my UnmarshalText the time I'm trying to parse is in the correct format for my type
You can also drop an fmt.Println("here") inside UnmarshalText and it won't get called
ah, time.Time has an UnmarshalJSON and you’re embedding it, so that takes precedence
idk https://go.dev/play/p/Uiu7lCkzFPa
may be will help somehow
Is the precedence documented somewhere? because if I have an UnmarshalJSON of my own that does seem to take precedence
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.
Ahhhh now I get it
Without my UnmarshalJSON hiding the one from time.Time it ends up using that
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)
eh, it is a little less than ideal but I guess I can just implement UnmarshalJSON and MarshalJSON and handle the quoting myself
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
so Unmarshal calls the method on embeded type first?
encoding/json first sees if the type implements json.Unmarshaler. that’s totally separate from embedding concerns