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
GODRIVER-1765 Improve JSON marshaling/unmarshaling for bson.D, bson.M and bson.A. #1594
base: master
Are you sure you want to change the base?
Conversation
e3e35d4
to
bbfb128
Compare
API Change Report./bson/primitivecompatible changes(*A).UnmarshalJSON: added |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM!
bson/primitive/primitive.go
Outdated
dec := json.NewDecoder(bytes.NewReader(b)) | ||
t, err := dec.Token() | ||
if err != nil { | ||
return err | ||
} | ||
if t == nil { | ||
*d = nil | ||
return nil | ||
} | ||
if v, ok := t.(json.Delim); !ok || v != '{' { | ||
return &json.UnmarshalTypeError{ | ||
Value: tokenString(t), | ||
Type: reflect.TypeOf(*d), | ||
Offset: dec.InputOffset(), | ||
} | ||
} | ||
*d, err = jsonDecodeD(dec) | ||
return err |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[Optional] You could combine the logic in D.UnmarshalJSON and m.UnmarshalJSON using generics:
func newJsonObjDecoder[T D | M](b []byte, val *T) (*json.Decoder, error) {
dec := json.NewDecoder(bytes.NewReader(b))
t, err := dec.Token()
if err != nil {
return nil, err
}
if t == nil {
*val = nil
return nil, nil
}
if v, ok := t.(json.Delim); !ok || v != '{' {
return nil, &json.UnmarshalTypeError{
Value: tokenString(t),
Type: reflect.TypeOf(*val),
Offset: dec.InputOffset(),
}
}
return dec, nil
}
GODRIVER-1765
Summary
This PR adds
json.Marshaler
andjson.Unmarshaler
forprimitive.D
, so it can handle JSON objects properly.The PR also adds
json.Unmarshaler
s forprimitive.M
andprimitive.A
, so JSON strings can be unmarshaled into nested structures correspondingly.After the "primitive" merging into "bson" package, we can migrate these
primitive
methods to theirbson
types.