File tree 1 file changed +31
-0
lines changed
1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change @@ -265,4 +265,35 @@ should.Equal(json.Number("123"), obj)
265
265
```
266
266
267
267
# 统一更改字段的命名风格
268
+
269
+ 经常 JSON 里的字段名 Go 里的字段名是不一样的。我们可以用 field tag 来修改。
270
+
271
+ ``` golang
272
+ output , err := jsoniter.Marshal (struct {
273
+ UserName string ` json:"user_name"`
274
+ FirstLanguage string ` json:"first_language"`
275
+ }{
276
+ UserName : " taowen" ,
277
+ FirstLanguage : " Chinese" ,
278
+ })
279
+ should.Equal (` {"user_name":"taowen","first_language":"Chinese"}` , string (output))
280
+ ```
281
+
282
+ 但是一个个字段来设置,太麻烦了。如果使用 jsoniter,我们可以统一设置命名风格。
283
+
284
+ ``` golang
285
+ import " github.com/json-iterator/go/extra"
286
+
287
+ extra.SetNamingStrategy (LowerCaseWithUnderscores)
288
+ output , err := jsoniter.Marshal (struct {
289
+ UserName string
290
+ FirstLanguage string
291
+ }{
292
+ UserName : " taowen" ,
293
+ FirstLanguage : " Chinese" ,
294
+ })
295
+ should.Nil (err)
296
+ should.Equal (` {"user_name":"taowen","first_language":"Chinese"}` , string (output))
297
+ ```
298
+
268
299
# 使用私有的字段
You can’t perform that action at this time.
0 commit comments