Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encoding/json: documented behavior unmarshaling JSON null into json.Unmarshaler is unclear #24903

Closed
anzdaddy opened this issue Apr 17, 2018 · 2 comments

Comments

@anzdaddy
Copy link

What version of Go are you using (go version)?

1.10.1

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

N/A

What did you do?

I read the documentation for json.Unmarshal and json.Unmarshaler.UnmarshalJSON, and the relevant code:

if v.IsNil() {
v.Set(reflect.New(v.Type().Elem()))
}
if v.Type().NumMethod() > 0 {
if u, ok := v.Interface().(Unmarshaler); ok {
return u, nil, reflect.Value{}
}
if !decodingNull {
if u, ok := v.Interface().(encoding.TextUnmarshaler); ok {
return nil, u, reflect.Value{}
}
}
}

What did you expect to see?

A statement to the effect that json.Unmarshal will zero the value before calling json.Unmarshaler.UnmarshalJSON.

What did you see instead?

According to the documentation, json.Unmarshal passes null to json.Unmarshaler.UnmarshalJSON. However, it doesn't explain that, prior to making the call, it sets the field to the zero value.

This is hinted at in the documentation for json.Unmarshaler, wherein it requires treating null inputs as a no-op, but this leaves the reader wondering what state the field is left in if it wasn't already the zero value.

@ianlancetaylor ianlancetaylor changed the title Documented behavior unmarshaling JSON null into json.Unmarshaler is unclear encoding/json: documented behavior unmarshaling JSON null into json.Unmarshaler is unclear Apr 17, 2018
@ianlancetaylor
Copy link
Contributor

But it doesn't set the field to the zero value. Consider:

https://play.golang.org/p/uNoEYH-UAqs

@anzdaddy
Copy link
Author

🤦 Sorry, I misread the if.

@golang golang locked and limited conversation to collaborators Apr 17, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants