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

jsonpb: fix Unmarshal when single enum value is provided for a repeated enum field #209

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
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
3 changes: 3 additions & 0 deletions jsonpb/jsonpb.go
Original file line number Diff line number Diff line change
Expand Up @@ -634,6 +634,9 @@ func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMe
target.Set(reflect.New(targetType.Elem()))
target = target.Elem()
}
if target.Kind() != reflect.Int32 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead this, in line 624, you can check whether the target can be an enum type.

maybeEnum := target.Kind() == reflect.Int32 ||
target.Kind() == reflect.Ptr && targetType.Elem().Kind() == reflect.Int32 // proto2
if maybeEnum && inputValue[0] == '"' && prop != nil && prop.Enum != "" {
...
}

The advantage is the case this change addresses will be handled by the json unmarshal code so the error message will be a bit clearer.

"json: cannot unmarshal string into Go value of type []json.RawMessage"
vs.
"mismatched type, want int32, got slice"

return fmt.Errorf("mismatched type, want %v, got %v", reflect.Int32, target.Kind())
}
target.SetInt(int64(n))
return nil
}
Expand Down
1 change: 1 addition & 0 deletions jsonpb/jsonpb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,7 @@ var unmarshalingShouldError = []struct {
{"gibberish", "{adskja123;l23=-=", new(pb.Simple)},
{"unknown field", `{"unknown": "foo"}`, new(pb.Simple)},
{"unknown enum name", `{"hilarity":"DAVE"}`, new(proto3pb.Message)},
{"single enum for repeated enum field", `{"r_color":"BLUE"}`, new(pb.Widget)},
}

func TestUnmarshalingBadInput(t *testing.T) {
Expand Down