Skip to content

Commit

Permalink
chore: refactoring mapping string to slice (#1959)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevwan committed Jun 3, 2022
1 parent 07145b2 commit b94b68a
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 15 deletions.
11 changes: 7 additions & 4 deletions core/mapping/unmarshaler.go
Expand Up @@ -496,17 +496,20 @@ func (u *Unmarshaler) fillSlice(fieldType reflect.Type, value reflect.Value, map
return nil
}

func (u *Unmarshaler) fillSliceFromString(fieldType reflect.Type, value reflect.Value, mapValue interface{}) error {
func (u *Unmarshaler) fillSliceFromString(fieldType reflect.Type, value reflect.Value,
mapValue interface{}) error {
var slice []interface{}
switch v := mapValue.(type) {
case json.Number:
case fmt.Stringer:
if err := jsonx.UnmarshalFromString(v.String(), &slice); err != nil {
return err
}
default:
if err := jsonx.UnmarshalFromString(mapValue.(string), &slice); err != nil {
case string:
if err := jsonx.UnmarshalFromString(v, &slice); err != nil {
return err
}
default:
return errUnsupportedType
}

baseFieldType := Deref(fieldType.Elem())
Expand Down
41 changes: 30 additions & 11 deletions core/mapping/unmarshaler_test.go
Expand Up @@ -2777,6 +2777,36 @@ func TestUnmarshalJsonReaderComplex(t *testing.T) {
assert.Equal(t, "txt", req.Txt)
}

func TestUnmarshalJsonReaderArrayBool(t *testing.T) {
payload := `{"id": false}`
var res struct {
ID []string `json:"id"`
}
reader := strings.NewReader(payload)
err := UnmarshalJsonReader(reader, &res)
assert.NotNil(t, err)
}

func TestUnmarshalJsonReaderArrayInt(t *testing.T) {
payload := `{"id": 123}`
var res struct {
ID []string `json:"id"`
}
reader := strings.NewReader(payload)
err := UnmarshalJsonReader(reader, &res)
assert.NotNil(t, err)
}

func TestUnmarshalJsonReaderArrayString(t *testing.T) {
payload := `{"id": "123"}`
var res struct {
ID []string `json:"id"`
}
reader := strings.NewReader(payload)
err := UnmarshalJsonReader(reader, &res)
assert.NotNil(t, err)
}

func BenchmarkDefaultValue(b *testing.B) {
for i := 0; i < b.N; i++ {
var a struct {
Expand All @@ -2789,14 +2819,3 @@ func BenchmarkDefaultValue(b *testing.B) {
}
}
}

func TestUnmarshalJsonReaderArray(t *testing.T) {
payload := "{\"id\": 123}"
var res struct {
ID []string `json:"id"`
}
reader := strings.NewReader(payload)
err := UnmarshalJsonReader(reader, &res)
assert.Nil(t, err)
assert.Equal(t, 1, len(res.ID))
}

0 comments on commit b94b68a

Please sign in to comment.