Skip to content

Commit be214ec

Browse files
authored
Update go-tips.cn.md
1 parent 6154bf5 commit be214ec

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

go-tips.cn.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,33 @@ jsoniter.UnmarshalFromString(`[]`, &val)
175175
```
176176

177177
# 使用 MarshalJSON支持time.Time
178+
179+
golang 是默认不支持 time.Time 序列化成 JSON 的。如果要支持,可以自定义 time.Time 类型
180+
181+
182+
```golang
183+
type timeImplementedMarshaler time.Time
184+
185+
func (obj timeImplementedMarshaler) MarshalJSON() ([]byte, error) {
186+
seconds := time.Time(obj).Unix()
187+
return []byte(strconv.FormatInt(seconds, 10)), nil
188+
}
189+
```
190+
191+
序列化的时候会调用 MarshalJSON
192+
193+
```golang
194+
type TestObject struct {
195+
Field timeImplementedMarshaler
196+
}
197+
should := require.New(t)
198+
val := timeImplementedMarshaler(time.Unix(123, 0))
199+
obj := TestObject{val}
200+
bytes, err := jsoniter.Marshal(obj)
201+
should.Nil(err)
202+
should.Equal(`{"Field":123}`, string(bytes))
203+
```
204+
178205
# 使用 RegisterTypeEncoder支持time.Time
179206
# 使用 MarshalText支持非字符串作为key的map
180207
# 使用 json.RawMessage

0 commit comments

Comments
 (0)