Skip to content

Commit

Permalink
Fix map/slice regression caused by liip#32
Browse files Browse the repository at this point in the history
Maps and slices that are nil are empty and valid.
The change introduced by liip#32 which fixes liip#31 has changed how
nil slices and maps are marshaled (`null` instead of `[]`).

Fix this regression by removing maps and slices from the check.
  • Loading branch information
simaotwx committed Sep 1, 2021
1 parent a143a78 commit f81ea9d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
2 changes: 1 addition & 1 deletion sheriff.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ func marshalValue(options *Options, v reflect.Value) (interface{}, error) {
k := v.Kind()

switch k {
case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
case reflect.Interface, reflect.Ptr:
if v.IsNil() {
return val, nil
}
Expand Down
32 changes: 30 additions & 2 deletions sheriff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -630,8 +630,8 @@ func TestMarshal_ArrayOfInterfaceable(t *testing.T) {
type TestInlineStruct struct {
// explicitly testing unexported fields
// golangci-lint complains about it and that's ok to ignore.
tableName struct{ Test string } `json:"-"` //nolint
tableNameWithTag struct{ Test string } `json:"foo"` //nolint
tableName struct{ Test string } `json:"-"` //nolint
tableNameWithTag struct{ Test string } `json:"foo"` //nolint

Field string `json:"field"`
Field2 *string `json:"field2"`
Expand Down Expand Up @@ -733,3 +733,31 @@ func TestMarshal_BooleanPtrMap(t *testing.T) {

assert.Equal(t, string(marshal), string(expect))
}

func TestMarshal_NilSlice(t *testing.T) {
var stringSlice []string // nil slice

marshalSlice, err := Marshal(&Options{}, stringSlice)
assert.NoError(t, err)

jsonResult, err := json.Marshal(marshalSlice)
assert.NoError(t, err)

expect := "[]"

assert.Equal(t, expect, string(jsonResult))
}

func TestMarshal_NilMap(t *testing.T) {
var stringMap map[string]string // nil map

marshalMap, err := Marshal(&Options{}, stringMap)
assert.NoError(t, err)

jsonResult, err := json.Marshal(marshalMap)
assert.NoError(t, err)

expect := "{}"

assert.Equal(t, expect, string(jsonResult))
}

0 comments on commit f81ea9d

Please sign in to comment.