是否可能:结构中有一个字段,但在 Golang 的序列化/反序列化过程中为它取不同的名称?
例如,我有结构“坐标”。
type Coordinates struct {
red int
}
对于 JSON 的反序列化,需要这样的格式:
{
"red":12
}
但是当我将结构序列化时,结果应该是这样的:
{
"r":12
}
最佳答案
标准库不支持开箱即用,但使用自定义 marshaler/unmarsaler你可以做任何你想做的事情。
例如:
type Coordinates struct {
Red int `json:"red"`
}
func (c Coordinates) MarshalJSON() ([]byte, error) {
type out struct {
R int `json:"r"`
}
return json.Marshal(out{R: c.Red})
}
(注意:必须导出结构字段才能参与编码/解码过程。)
测试它:
s := `{"red":12}`
var c Coordinates
if err := json.Unmarshal([]byte(s), &c); err != nil {
panic(err)
}
out, err := json.Marshal(c)
if err != nil {
panic(err)
}
fmt.Println(string(out))
输出(在 Go Playground 上尝试):
{"r":12}
关于json - golang序列化反序列化时JSON属性名称不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67303521/