gpt4 book ai didi

go - 编码为 JSON 时将类型 int 转换为 const 名称的字符串

转载 作者:IT王子 更新时间:2023-10-29 02:31:30 27 4
gpt4 key购买 nike

我有一个看起来像这样的结构:

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 }

最佳答案

您需要为您的类型定义自定义编码器。

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 应如何编码(marshal)您的类型。如果您还需要朝另一个方向前进,则可以对解码执行类似的操作。

参见 https://play.golang.org/p/mLxThWA19by .

关于go - 编码为 JSON 时将类型 int 转换为 const 名称的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51695573/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com