Skip to content

Commit ecd743b

Browse files
committed
test unmarshal with ignored field and fix error message
1 parent 109b46a commit ecd743b

File tree

3 files changed

+21
-4
lines changed

3 files changed

+21
-4
lines changed

jsonapi/fixtures_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ func (u *User) SetID(stringID string) error {
6868
type SimplePost struct {
6969
ID string `jsonapi:"-"`
7070
Title, Text string
71+
Internal string `jsonapi:"-"`
7172
Size int
7273
Created time.Time `jsonapi:"name=create-date"`
7374
}

jsonapi/unmarshal.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -256,19 +256,20 @@ func UnmarshalInto(input map[string]interface{}, targetStructType reflect.Type,
256256
fieldName := Dejsonify(key)
257257
field := val.FieldByName(fieldName)
258258
fieldType, found := val.Type().FieldByName(fieldName)
259-
if !found || found && fieldType.Tag.Get("jsonapi") == "-" {
259+
if !found {
260260
//check if there is any field tag with the given name available
261261
for x := 0; x < val.NumField(); x++ {
262262
tfield := val.Type().Field(x)
263263
name := GetTagValueByName(tfield, "name")
264264
if tfield.Tag.Get("jsonapi") != "-" && strings.ToLower(name) == strings.ToLower(fieldName) {
265265
field = val.Field(x)
266+
found = true
266267
}
267268
}
268269

269-
if !field.IsValid() {
270-
return errors.New("expected struct " + targetStructType.Name() + " to have field " + fieldName)
271-
}
270+
}
271+
if !found || fieldType.Tag.Get("jsonapi") == "-" {
272+
return fmt.Errorf("invalid key \"%s\" in json. Cannot be assigned to target struct \"%s\"", key, targetStructType.Name())
272273
}
273274

274275
value := reflect.ValueOf(attributeValue)

jsonapi/unmarshal_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,21 @@ var _ = Describe("Unmarshal", func() {
125125
Expect(err).To(HaveOccurred())
126126
})
127127

128+
It("errors if a field is in the json that is ignored by the struct", func() {
129+
var post SimplePost
130+
err := Unmarshal(map[string]interface{}{
131+
"data": map[string]interface{}{
132+
"id": "1234",
133+
"attributes": map[string]interface{}{
134+
"title": "something",
135+
"text": "blubb",
136+
"internal": "1337",
137+
},
138+
},
139+
}, &post)
140+
Expect(err.Error()).To(Equal("invalid key \"internal\" in json. Cannot be assigned to target struct \"SimplePost\""))
141+
})
142+
128143
It("errors with wrong type, expected int, got a string", func() {
129144
var posts []SimplePost
130145
err := Unmarshal(map[string]interface{}{

0 commit comments

Comments
 (0)