Go 中带有 JSON Marshal 的小写 JSON 键名 [英] Lowercase JSON key names with JSON Marshal in Go

查看:30
本文介绍了Go 中带有 JSON Marshal 的小写 JSON 键名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用 "encoding/json" 包来编组在我的应用程序的导入包之一中声明的结构.

I wish to use the "encoding/json" package to marshal a struct declared in one of the imported packages of my application.

例如:

type T struct {
    Foo int
}

因为是导入的,所以结构体中所有可用(导出)的字段都以大写字母开头.但我希望有小写的键名:

Because it is imported, all available (exported) fields in the struct begins with an upper case letter. But I wish to have lower case key names:

out, err := json.Marshal(&T{Foo: 42})

将导致

{"Foo":42}

但我想得到

{"foo":42}

是否有可能以某种简单的方式解决问题?

Is it possible to get around the problem in some easy way?

推荐答案

查看 编码/json.Marshal.它讨论了使用 struct 字段标记来确定生成的 json 的格式.

Have a look at the docs for encoding/json.Marshal. It discusses using struct field tags to determine how the generated json is formatted.

例如:

type T struct {
    FieldA int    `json:"field_a"`
    FieldB string `json:"field_b,omitempty"`
}

这将生成如下 JSON:

This will generate JSON as follows:

{
    "field_a": 1234,
    "field_b": "foobar"
}

这篇关于Go 中带有 JSON Marshal 的小写 JSON 键名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆