Skip to content

jsonpb: emit null value for oneof field with 'nil-interface' value #582

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

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions jsonpb/jsonpb.go
Original file line number Diff line number Diff line change
Expand Up @@ -316,9 +316,15 @@ func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeU
// Oneof fields need special handling.
if valueField.Tag.Get("protobuf_oneof") != "" {
// value is an interface containing &T{real_value}.
sv := value.Elem().Elem() // interface -> *T -> T
value = sv.Field(0)
valueField = sv.Type().Field(0)
svPtr := value.Elem() // interface -> *T
if !svPtr.IsNil() {
sv := svPtr.Elem() // *T -> T
value = sv.Field(0)
valueField = sv.Type().Field(0)
} else {
value = reflect.ValueOf(nil)
valueField = svPtr.Type().Elem().Field(0)
}
}
prop := jsonProperties(valueField, m.OrigName)
if !firstField {
Expand Down Expand Up @@ -934,6 +940,13 @@ func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMe
if !ok {
continue
}

if string(raw) == "null" {
nv := reflect.New(reflect.PtrTo(oop.Type.Elem()))
target.Field(oop.Field).Set(nv.Elem())
continue
}

nv := reflect.New(oop.Type.Elem())
target.Field(oop.Field).Set(nv)
if err := u.unmarshalValue(nv.Elem().Field(0), raw, oop.Prop); err != nil {
Expand Down