【发布时间】:2021-07-22 00:06:05
【问题描述】:
是否有可能:结构中有一个字段,但在 Golang 中的序列化/反序列化期间它的名称不同?
例如,我有结构“坐标”。
type Coordinates struct {
red int
}
对于 JSON 的反序列化,希望有这样的格式:
{
"red":12
}
但是当我将结构体序列化时,结果应该是这样的:
{
"r":12
}
【问题讨论】:
是否有可能:结构中有一个字段,但在 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}
【讨论】:
有几种选择:
type Coordinates1 struct {
Red int `json:"red"`
}
type Coordinates2 struct {
Red int `json:"r"`
}
// Cast from first to second:
var x Coordinates1
json.Unmarshal(data,&x)
y:=*(*Coordinates2)(&x)
json.Marshal(y)
【讨论】:
Marshal 和/或Unmarshal 方法。