// Package dynamicstruct ... // // Description : dynamic struct ... // // Author : go_developer@163.com<白茶清欢> // // Date : 2025-03-19 14:48 package dynamicstruct import ( "encoding/json" "fmt" "reflect" "testing" ) func Test_dynamicStructImpl_New(t *testing.T) { instance := NewStruct(map[string]string{}). /*AddField("Integer", "", 0, `json:"int"`, false). AddField("Text", "", "", `json:"someText"`, false). AddField("Float", "", 0.0, `json:"double"`, false). AddField("Boolean", "", false, "", false). AddField("Slice", "", []int{}, "", false). AddField("Anonymous", "", "", `json:"-"`, false).*/ AddField("user.base.age", "", 20, `json:"age"`, false). AddField("user.base.name", "", "", `json:"name"`, false). AddField("user.job.address", "", "", `json:"address"`, false). AddField("user.job.company.name", "", "", `json:"name"`, false). AddField("arr.[].item.name", "", "", `json:"name"`, false). AddField("arr2.[].[].item.name", "", "", `json:"name"`, false). Build() val := instance.New() data := []byte(` { "int": 123, "someText": "example", "double": 123.45, "Boolean": true, "Slice": [1, 2, 3], "user": {"job":{"address":"beijing","company":{"name":"unknown"}}, "base":{"age": 1800, "name":"baicha"}}, "Anonymous": "avoid to read", "arr": [{"item":{"name":"item1","test":1}},{"item":{"name":"item2", "test":2}}], "arr2": [[{"item":{"name":"item1","test":1}},{"item":{"name":"item2", "test":2}}]] } `) tType := reflect.TypeOf(val) fmt.Println(tType, tType.Kind(), tType.Elem().Kind(), tType.Elem().Kind().String()) err := json.Unmarshal(data, &val) fmt.Println(err, val) valByte, _ := json.Marshal(val) fmt.Println(string(valByte)) // fmt.Println(reflect.ValueOf(val).Elem().FieldByName("Integer").Interface()) }