From 07145b210ed4acf4a67fb14936fa24f8cfca3b94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AE=B6=E7=A6=8F?= <30451714+cjf8134@users.noreply.github.com> Date: Fri, 3 Jun 2022 00:27:48 +0800 Subject: [PATCH] fix: panic on convert to string on fillSliceFromString() (#1951) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Update unmarshaler.go fix: 修复fillSliceFromString()方法中mapValue 强转string后的panic 错误 * test: 增加单元测试 增加单元测试 * Update unmarshaler_test.go --- core/mapping/unmarshaler.go | 11 +++++++++-- core/mapping/unmarshaler_test.go | 11 +++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/core/mapping/unmarshaler.go b/core/mapping/unmarshaler.go index b86ef8f4..56e58839 100644 --- a/core/mapping/unmarshaler.go +++ b/core/mapping/unmarshaler.go @@ -498,8 +498,15 @@ func (u *Unmarshaler) fillSlice(fieldType reflect.Type, value reflect.Value, map func (u *Unmarshaler) fillSliceFromString(fieldType reflect.Type, value reflect.Value, mapValue interface{}) error { var slice []interface{} - if err := jsonx.UnmarshalFromString(mapValue.(string), &slice); err != nil { - return err + switch v := mapValue.(type) { + case json.Number: + if err := jsonx.UnmarshalFromString(v.String(), &slice); err != nil { + return err + } + default: + if err := jsonx.UnmarshalFromString(mapValue.(string), &slice); err != nil { + return err + } } baseFieldType := Deref(fieldType.Elem()) diff --git a/core/mapping/unmarshaler_test.go b/core/mapping/unmarshaler_test.go index 0bf1739c..f3b037f0 100644 --- a/core/mapping/unmarshaler_test.go +++ b/core/mapping/unmarshaler_test.go @@ -2789,3 +2789,14 @@ 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)) +}