feat: 字符串转struct slice

This commit is contained in:
2025-10-13 15:21:33 +08:00
parent 033e013510
commit 80b5e4e7cc
5 changed files with 94 additions and 11 deletions

View File

@ -8,8 +8,10 @@
package op_string
import (
"encoding/json"
"testing"
"git.zhangdeman.cn/zhangdeman/serialize"
. "github.com/smartystreets/goconvey/convey"
)
@ -37,9 +39,38 @@ func TestToBaseTypeSlice(t *testing.T) {
})
Convey("字符串转数组失败", t, func() {
testData := `1,2,3,4,-5`
res := ToBaseTypeSlice[uint](testData)
res := ToBaseTypeSlice[uint](testData, ",")
So(res.Value, ShouldNotBeNil)
So(len(res.Value), ShouldEqual, 0)
So(res.Err, ShouldNotBeNil)
serialize.JSON.ConsoleOutput(res)
})
}
func TestToMapSlice(t *testing.T) {
Convey("序列化数据转map数组成功", t, func() {
testData := `[{"name":"baicha", "age": 18}]`
res := ToMapSlice[string, any](testData)
So(res.Value, ShouldNotBeNil)
So(res.Err, ShouldBeNil)
So(len(res.Value), ShouldEqual, 1)
So(res.Value[0]["name"], ShouldEqual, "baicha")
So(res.Value[0]["age"], ShouldEqual, json.Number("18"))
})
}
func TestToStructSlice(t *testing.T) {
Convey("序列化数据转map数组成功", t, func() {
testData := `[{"name":"baicha", "age": 18}]`
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
res := ToStructSlice[User](testData)
So(res.Value, ShouldNotBeNil)
So(res.Err, ShouldBeNil)
So(len(res.Value), ShouldEqual, 1)
So(res.Value[0].Name, ShouldEqual, "baicha")
So(res.Value[0].Age, ShouldEqual, 18)
})
}