github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/ztype/struct_test.go (about) 1 package ztype_test 2 3 import ( 4 "reflect" 5 "testing" 6 7 "github.com/sohaha/zlsgo" 8 "github.com/sohaha/zlsgo/zjson" 9 "github.com/sohaha/zlsgo/ztype" 10 ) 11 12 func TestNewStruct(t *testing.T) { 13 tt := zlsgo.NewTest(t) 14 15 s := ztype.NewStruct() 16 s.AddField("Name", "") 17 s.AddField("Age", reflect.TypeOf(1), `json:"age"`) 18 data := `{"Name":"test","age":33}` 19 v := s.Interface() 20 err := zjson.Unmarshal(data, v) 21 tt.NoError(err) 22 t.Logf("%+v\n", v) 23 24 childS := ztype.NewStruct() 25 childS.AddField("Name", "") 26 childS.AddField("Child", s, `json:"child"`) 27 v2 := childS.Interface() 28 data2 := `{"Name":"testChild","child":` + data + `}` 29 err = zjson.Unmarshal(data2, v2) 30 tt.NoError(err) 31 t.Logf("%+v\n", v2) 32 } 33 34 func TestNewSliceStruct(t *testing.T) { 35 tt := zlsgo.NewTest(t) 36 37 s := ztype.NewSliceStruct() 38 s.AddField("Name", "") 39 s.AddField("Age", reflect.TypeOf(1), `json:"age"`) 40 data := `[{"Name":"test","age":33},{"Name":"test2","age":100}]` 41 v := s.Interface() 42 err := zjson.Unmarshal(data, v) 43 tt.NoError(err) 44 t.Logf("%+v %s\n", v, data) 45 46 childS := ztype.NewSliceStruct() 47 childS.AddField("Name", "") 48 childS.AddField("Child", s, `json:"child"`) 49 v2 := childS.Interface() 50 data2 := `[{"Name":"testChild","child":` + data + `}]` 51 err = zjson.Unmarshal(data2, v2) 52 tt.NoError(err) 53 t.Logf("%+v %s\n", v2, data2) 54 } 55 56 func TestNewMapStruct(t *testing.T) { 57 tt := zlsgo.NewTest(t) 58 59 s := ztype.NewMapStruct("") 60 s.AddField("Name", "") 61 s.AddField("Age", reflect.TypeOf(1), `json:"age"`) 62 data := `{"test1":{"Name":"11","age":33},"test2":{"Name":"22","age":99}}` 63 v := s.Interface() 64 err := zjson.Unmarshal(data, v) 65 tt.NoError(err) 66 t.Logf("%+v %s\n", v, data) 67 68 childS := ztype.NewMapStruct("") 69 childS.AddField("Name", "") 70 childS.AddField("Child", s, `json:"child"`) 71 v2 := childS.Interface() 72 data2 := `{"test1":{"Name":"testChild","child":` + data + `}}` 73 err = zjson.Unmarshal(data2, v2) 74 tt.NoError(err) 75 t.Logf("%+v %s\n", v2, data2) 76 } 77 78 type testStruct struct { 79 Name string 80 } 81 82 func (t *testStruct) Alias() string { 83 return "Alias_" + t.Name 84 }