Skip to content

Commit

Permalink
Merge pull request #7 from greensnark/fix-map-deserialize
Browse files Browse the repository at this point in the history
Fix panic on unmarshal for maps with struct pointer values
  • Loading branch information
Sam Ghods authored Dec 7, 2016
2 parents a54de18 + e9369f6 commit 04f3134
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
6 changes: 5 additions & 1 deletion fields.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,11 @@ func indirect(v reflect.Value, decodingNull bool) (json.Unmarshaler, encoding.Te
break
}
if v.IsNil() {
v.Set(reflect.New(v.Type().Elem()))
if v.CanSet() {
v.Set(reflect.New(v.Type().Elem()))
} else {
v = reflect.New(v.Type().Elem())
}
}
if v.Type().NumMethod() > 0 {
if u, ok := v.Interface().(json.Unmarshaler); ok {
Expand Down
16 changes: 16 additions & 0 deletions yaml_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,22 @@ func TestUnmarshal(t *testing.T) {
s4 := UnmarshalStringMap{}
e4 := UnmarshalStringMap{map[string]string{"b": "1"}}
unmarshal(t, y, &s4, &e4)

y = []byte(`
a:
name: TestA
b:
name: TestB
`)
type NamedThing struct {
Name string `json:"name"`
}
s5 := map[string]*NamedThing{}
e5 := map[string]*NamedThing{
"a": &NamedThing{Name: "TestA"},
"b": &NamedThing{Name: "TestB"},
}
unmarshal(t, y, &s5, &e5)
}

func unmarshal(t *testing.T, y []byte, s, e interface{}) {
Expand Down

0 comments on commit 04f3134

Please sign in to comment.