github.com/gogf/gf@v1.16.9/os/gtime/gtime_z_unit_json_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gtime_test 8 9 import ( 10 "github.com/gogf/gf/internal/json" 11 "github.com/gogf/gf/os/gtime" 12 "github.com/gogf/gf/test/gtest" 13 "testing" 14 ) 15 16 func Test_Json_Pointer(t *testing.T) { 17 // Marshal 18 gtest.C(t, func(t *gtest.T) { 19 type T struct { 20 Time *gtime.Time 21 } 22 t1 := new(T) 23 s := "2006-01-02 15:04:05" 24 t1.Time = gtime.NewFromStr(s) 25 j, err := json.Marshal(t1) 26 t.Assert(err, nil) 27 t.Assert(j, `{"Time":"2006-01-02 15:04:05"}`) 28 }) 29 // Marshal nil 30 gtest.C(t, func(t *gtest.T) { 31 type T struct { 32 Time *gtime.Time 33 } 34 t1 := new(T) 35 j, err := json.Marshal(t1) 36 t.Assert(err, nil) 37 t.Assert(j, `{"Time":null}`) 38 }) 39 // Marshal nil omitempty 40 gtest.C(t, func(t *gtest.T) { 41 type T struct { 42 Time *gtime.Time `json:"time,omitempty"` 43 } 44 t1 := new(T) 45 j, err := json.Marshal(t1) 46 t.Assert(err, nil) 47 t.Assert(j, `{}`) 48 }) 49 // Unmarshal 50 gtest.C(t, func(t *gtest.T) { 51 var t1 gtime.Time 52 s := []byte(`"2006-01-02 15:04:05"`) 53 err := json.UnmarshalUseNumber(s, &t1) 54 t.Assert(err, nil) 55 t.Assert(t1.String(), "2006-01-02 15:04:05") 56 }) 57 } 58 59 func Test_Json_Struct(t *testing.T) { 60 // Marshal 61 gtest.C(t, func(t *gtest.T) { 62 type T struct { 63 Time gtime.Time 64 } 65 t1 := new(T) 66 s := "2006-01-02 15:04:05" 67 t1.Time = *gtime.NewFromStr(s) 68 j, err := json.Marshal(t1) 69 t.Assert(err, nil) 70 t.Assert(j, `{"Time":"2006-01-02 15:04:05"}`) 71 }) 72 // Marshal nil 73 gtest.C(t, func(t *gtest.T) { 74 type T struct { 75 Time gtime.Time 76 } 77 t1 := new(T) 78 j, err := json.Marshal(t1) 79 t.Assert(err, nil) 80 t.Assert(j, `{"Time":""}`) 81 }) 82 // Marshal nil omitempty 83 gtest.C(t, func(t *gtest.T) { 84 type T struct { 85 Time gtime.Time `json:"time,omitempty"` 86 } 87 t1 := new(T) 88 j, err := json.Marshal(t1) 89 t.Assert(err, nil) 90 t.Assert(j, `{"time":""}`) 91 }) 92 93 }