go - 编组为 JSON 时将类型 int 转换为 const 名称的字符串
问题描述
我有一个看起来像这样的结构:
type Type int
const (
A Type = iota
B
C
)
type Character struct {
Type Type `json:"type"`
}
当我调用json.Marshal(...)
该结构时,有没有一种方法可以json:"type"
表示是一个名为"A"
,"B"
或 " C
" 的字符串?
当它以 JSON 形式呈现时,没有人会知道0
、1
或2
是什么,因此常量的名称更有用。
抱歉,如果以前有人问过这个问题。我用谷歌搜索了一遍,找不到任何东西。
这是一个例子:
type Type int
const (
A Type = iota
B
C
)
type Character struct {
Type Type `json:"type,string"`
}
func main() {
c := Character{}
c.Type = A
j, err := json.Marshal(c)
if err != nil {
panic(err)
}
fmt.Println(string(j))
}
我要fmt.Println(string(j))
打印{"type":"A"}
,不是{"type":0}
。
解决方案
您需要为您的类型定义一个自定义编组器。
type Type int
const (
A Type = iota
B
C
)
var typeToString = map[Type]string{
A: "A",
B: "B",
C: "C",
}
func (t Type) MarshalJSON() ([]byte, error) {
return json.Marshal(typeToString[t])
}
type Character struct {
Type Type `json:"type"`
}
func main() {
c := Character{}
c.Type = A
j, err := json.Marshal(c)
if err != nil {
panic(err)
}
fmt.Println(string(j))
}
该函数MarshalJSON
定义了json.Marshal
应该如何编组你的类型。如果您还需要朝另一个方向发展,您可以为解组做类似的事情。
推荐阅读
- python-3.x - 用一组元组制作扑克游戏
- reactjs - 为什么我会收到此错误:“在 './src' 中找不到文件 './App'。”:?
- python - 尝试创建热图时出错:“int”和“str”实例之间不支持“<=”
- elf - 如何查找 ppc 的重定位表信息
- python - django查询集中的sql字符串无法在pymysql中执行?
- django - 如何更新扩展的 Django 用户模型?
- intellij-idea - 如何让版本控制选项卡出现在 intellij 中?
- html - 引导,容器流体类不能改变填充
- excel - 如何将 VBA 函数应用于选定范围并将结果粘贴到同一范围?
- javascript - 在控制台中显示值 shoe false