File tree 1 file changed +27
-0
lines changed 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change @@ -175,6 +175,33 @@ jsoniter.UnmarshalFromString(`[]`, &val)
175
175
```
176
176
177
177
# 使用 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
+
178
205
# 使用 RegisterTypeEncoder支持time.Time
179
206
# 使用 MarshalText支持非字符串作为key的map
180
207
# 使用 json.RawMessage
You can’t perform that action at this time.
0 commit comments