首页 > 解决方案 > 编组为 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 形式呈现时,没有人会知道012是什么,因此常量的名称更有用。

抱歉,如果以前有人问过这个问题。我用谷歌搜索了一遍,找不到任何东西。

这是一个例子:

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}

标签: go

解决方案


您需要为您的类型定义一个自定义编组器。

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应该如何编组你的类型。如果您还需要朝另一个方向发展,您可以为解组做类似的事情。

请参阅https://play.golang.org/p/mLxThWA19by


推荐阅读