支持传入的跟结构就是数组

This commit is contained in:
2025-03-23 20:54:35 +08:00
parent 0b609e8e26
commit bc91937116
4 changed files with 83 additions and 10 deletions

View File

@ -223,3 +223,45 @@ func TestExtendStruct(t *testing.T) {
So(instance.GetField("Age").GetTag(), ShouldEqual, `json:"company_age"`)
})
}
func TestArrayRoot(t *testing.T) {
Convey("嵌套结构体带多级数组", t, func() {
data := []byte(`
[[[{
"age": 123,
"name": "example",
"double": 123.45,
"bool": true,
"slice": [1, 2, 3]
}]]]
`)
instance := NewStruct(map[string]string{
"test_tag_map": `json:"tag_map"`,
}).
AddField("[].[].[].age", "", 0, `json:"age"`, false).
AddField("[].[].[].name", "", "", `json:"name"`, false).
Build()
val := instance.New()
err := json.Unmarshal(data, &val)
So(err, ShouldBeNil)
reflectType := reflect.TypeOf(val)
// 需要是数组类型
So(reflectType.Kind(), ShouldEqual, reflect.Ptr)
So(reflectType.Elem().Kind(), ShouldEqual, reflect.Slice)
// 验证数据
// 数据序列化成功
targetByte, targetErr := json.Marshal(val)
So(targetErr, ShouldBeNil)
// 数据转map成功
var res [][][]any
targetUnmarshalErr := json.Unmarshal(targetByte, &res)
So(targetUnmarshalErr, ShouldBeNil)
So(len(res), ShouldEqual, 1)
userMap, ok := res[0][0][0].(map[string]any)
So(ok, ShouldBeTrue)
So(len(userMap), ShouldEqual, 2)
So(userMap["age"], ShouldEqual, float64(123))
So(userMap["name"], ShouldEqual, "example")
So(userMap["double"], ShouldBeNil)
})
}