Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: refactoring mapping string to slice #1959

Merged
merged 1 commit into from Jun 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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))
}