forked from Mirrors/jsonapi
fixes issue with slice of nil pointers (#144)
fixes panic in case of marshaling of slice of nils like `[]*<SomeType>{nil, nil}`
This commit is contained in:
parent
2dcc18f436
commit
5d047c6bc6
|
@ -207,9 +207,13 @@ func visitModelNode(model interface{}, included *map[string]*Node,
|
|||
node := new(Node)
|
||||
|
||||
var er error
|
||||
value := reflect.ValueOf(model)
|
||||
if value.IsNil() {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
modelValue := reflect.ValueOf(model).Elem()
|
||||
modelType := reflect.ValueOf(model).Type().Elem()
|
||||
modelValue := value.Elem()
|
||||
modelType := value.Type().Elem()
|
||||
|
||||
for i := 0; i < modelValue.NumField(); i++ {
|
||||
structField := modelValue.Type().Field(i)
|
||||
|
|
|
@ -37,6 +37,36 @@ func TestMarshalPayload(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestMarshalPayloadWithNulls(t *testing.T) {
|
||||
|
||||
books := []*Book{nil, {ID:101}, nil}
|
||||
var jsonData map[string]interface{}
|
||||
|
||||
|
||||
out := bytes.NewBuffer(nil)
|
||||
if err := MarshalPayload(out, books); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(out.Bytes(), &jsonData); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, ok := jsonData["data"]
|
||||
if !ok {
|
||||
t.Fatalf("data key does not exist")
|
||||
}
|
||||
arr, ok := raw.([]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("data is not an Array")
|
||||
}
|
||||
for i := 0; i < len(arr); i++ {
|
||||
if books[i] == nil && arr[i] != nil ||
|
||||
books[i] != nil && arr[i] == nil {
|
||||
t.Fatalf("restored data is not equal to source")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarshal_attrStringSlice(t *testing.T) {
|
||||
tags := []string{"fiction", "sale"}
|
||||
b := &Book{ID: 1, Tags: tags}
|
||||
|
|
Loading…
Reference in New Issue