-
Notifications
You must be signed in to change notification settings - Fork 17.9k
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: Marshaler/Unmarshaler not stream friendly #12001
Comments
This would be really nice to have. I looked a bit into the code and found that it won't be easy to use the However, it's more easy to have this implemented when using |
I think it's worth considering looking at the way the yaml package handles custom unmarshallers.
While I would normally dislike empty interfaces when it comes to marshalling its kind of unavoidable. What I like about this is it allows the object so simply inject the marshallable type it wishes to use under the hood without exposing a raw byte string. This has a nice side effect of decoupling the encoding from the object. For example, rather than this be a MarshalYAML and UnmarshalYAML interface this could just be Marshal and Unmarshal. This is nice because it breaks dependancies, moreover, the user just needs to specify the underlying marshalling type and it doesn't really care if it's decoded as a stream or a buffer. It's completely agnostic to that. |
The linked issue #14750 is not dependent on or directly related to this issue. It just raises another potential use-case for the described interface. The use-case is relevant for the described const jsonExample = `{"a": "foo", "b": "bar", "c": 42}`
type T struct {
A string
B string
C interface{}
}
func (t *T) DecodeJSON(dec json.Decoder) error {
// Rely on parent decoder option for DissalowUnknownFields.
dec.UseNumber() // Override UseNumber for sub-decoder only.
return dec.Decode(t)
} |
The Marshaler/Unmarshaler interface deals with whole []byte slices:
If you're dealing with a type that encodes to an array that has a large number of objects inside you have to encode all of into a single []byte.
The encoding/xml package is, unlike encoding/json, stream friendly:
With MarshalXML you can call e.Encode/e.EncodeElement/e.EncodeToken.
Since encoding/json is gaining Token()/EncodeToken() methods it would be really helpful to have a Marshaler/Unmarshaler interface that can take advantage of that. Perhaps something along the lines of:
Since Marshaler/Unmarshaler can't be changed. Or something like:
The text was updated successfully, but these errors were encountered: