Skip to content

Commit aceb337

Browse files
authored
Update go-tips.cn.md
1 parent d518460 commit aceb337

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

go-tips.cn.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,4 +265,35 @@ should.Equal(json.Number("123"), obj)
265265
```
266266

267267
# 统一更改字段的命名风格
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+
268299
# 使用私有的字段

0 commit comments

Comments
 (0)