Skip to content

Add a callback to jsonpb.Unmarshaler to report unknown fields. #415

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
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
25 changes: 18 additions & 7 deletions jsonpb/jsonpb.go
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,10 @@ type Unmarshaler struct {
// Whether to allow messages to contain unknown fields, as opposed to
// failing to unmarshal.
AllowUnknownFields bool

// If non-nil, AllowedUnknownField will be called for each unknown field
// encountered and allowed during the unmarshalling.
AllowedUnknownField func(fieldName string)
}

// UnmarshalNext unmarshals the next protocol buffer from a JSON object stream.
Expand Down Expand Up @@ -901,14 +905,21 @@ func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMe
}
}
}
if !u.AllowUnknownFields && len(jsonFields) > 0 {
// Pick any field to be the scapegoat.
var f string
for fname := range jsonFields {
f = fname
break
if len(jsonFields) > 0 {
if !u.AllowUnknownFields {
// Pick any field to be the scapegoat.
var f string
for fname := range jsonFields {
f = fname
break
}
return fmt.Errorf("unknown field %q in %v", f, targetType)
}
if u.AllowedUnknownField != nil {
for fname := range jsonFields {
u.AllowedUnknownField(fname)
}
}
return fmt.Errorf("unknown field %q in %v", f, targetType)
}
return nil
}
Expand Down
20 changes: 20 additions & 0 deletions jsonpb/jsonpb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import (
"io"
"math"
"reflect"
"sort"
"strings"
"testing"

Expand Down Expand Up @@ -665,6 +666,25 @@ func TestUnmarshalNullObject(t *testing.T) {
}
}

func TestUnmarshalAllowedUnknownFields(t *testing.T) {
var msg pb.Simple
var unknownFields []string
unmarshaler := &Unmarshaler{
AllowUnknownFields: true,
AllowedUnknownField: func(fname string) {
unknownFields = append(unknownFields, fname)
},
}
json := `{"oBool": true, "unknown-a": null, "unknown-b": null}`
if err := unmarshaler.Unmarshal(strings.NewReader(json), &msg); err != nil {
t.Fatal(err)
}
sort.Strings(unknownFields) // order of fields is unspecified
if want := []string{"unknown-a", "unknown-b"}; !reflect.DeepEqual(unknownFields, want) {
t.Errorf("got %v want %v", unknownFields, want)
}
}

func TestUnmarshalNext(t *testing.T) {
// We only need to check against a few, not all of them.
tests := unmarshalingTests[:5]
Expand Down