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

@ -16,7 +16,7 @@ import (
)
func TestToMap(t *testing.T) {
Convey("map[string]any转换成", t, func() {
Convey("map[string]any转换成", t, func() {
testData := `{
"name": "baicha",
"age": 18
@ -27,10 +27,19 @@ func TestToMap(t *testing.T) {
So(res.Value["name"], ShouldEqual, "baicha")
So(res.Value["age"], ShouldEqual, json.Number("18"))
})
Convey("map[string]any转换失败", t, func() {
testData := `
"name": "baicha",
"age": 18
}`
res := ToMap[string, any](testData)
So(res.Err, ShouldNotBeNil)
So(res.Value, ShouldBeNil)
})
}
func TestToStruct(t *testing.T) {
Convey("struct转换成", t, func() {
Convey("struct转换成", t, func() {
testData := `{
"name": "baicha",
"age": 18
@ -47,4 +56,21 @@ func TestToStruct(t *testing.T) {
So(res.Value.Name, ShouldEqual, "baicha")
So(res.Value.Age, ShouldEqual, 18)
})
Convey("struct转换失败", t, func() {
testData := `
"name": "baicha",
"age": 18
}`
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
var u User
res := ToStruct(testData, &u)
So(res.Err, ShouldNotBeNil)
So(res.Value, ShouldNotBeNil)
So(res.Value.Name, ShouldEqual, "")
So(res.Value.Age, ShouldEqual, 0)
})
}