Skip to content

Commit

Permalink
fix: unmarshal null into a struct (#15)
Browse files Browse the repository at this point in the history
Fixes #14
  • Loading branch information
blgm committed Sep 23, 2020
1 parent 097bc04 commit 1474c63
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
14 changes: 3 additions & 11 deletions unmarshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func Unmarshal(data []byte, receiver interface{}) error {
}

func unmarshalIntoStruct(ctx context.Context, target reflect.Value, found bool, source interface{}) error {
if !found {
if !found || source == nil {
return nil
}

Expand Down Expand Up @@ -163,11 +163,7 @@ func unmarshalInfoLeaf(ctx context.Context, target reflect.Value, found bool, so
}

func unmarshalIntoSlice(ctx context.Context, target reflect.Value, found bool, source interface{}) error {
if !found {
return nil
}

if source == nil {
if !found || source == nil {
return nil
}

Expand Down Expand Up @@ -196,11 +192,7 @@ func unmarshalIntoMap(ctx context.Context, target reflect.Value, found bool, sou
return newUnsupportedKeyTypeError(ctx, targetType.Key())
}

if !found {
return nil
}

if source == nil {
if !found || source == nil {
return nil
}

Expand Down
15 changes: 14 additions & 1 deletion unmarshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,19 @@ var _ = Describe("Unmarshal", func() {
Expect(s.W).To(BeTrue())
})

It("leaves struct types untouched", func() {
type b struct{ B string }

s := struct {
A b
}{
A: b{B: "hello"},
}

unmarshal(&s, `{"A": null}`)
Expect(s.A.B).To(Equal("hello"))
})

It("overwrites a pointer as nil", func() {
v := "hello"
s := struct{ S *string }{S: &v}
Expand Down Expand Up @@ -492,7 +505,7 @@ var _ = Describe("Unmarshal", func() {
unmarshal(&s, `{"T":[{"S":"foo"},{"S":"bar"},{},{"S":"baz"}]}`)
Expect(s.T).To(Equal([]t{{S: "foo"}, {S: "bar"}, {}, {S: "baz"}}))

expectToFail(&s, `{"T":[null]}`, `cannot unmarshal "<nil>" into index 0 (type "jsonry_test.t") path T[0]`)
expectToFail(&s, `{"T":[4]}`, `cannot unmarshal "4" type "number" into index 0 (type "jsonry_test.t") path T[0]`)
})

It("unmarshals a map of structs", func() {
Expand Down

0 comments on commit 1474c63

Please sign in to comment.