golang序列化和反序列化过程中JSON属性的不同名称

Gau*_*mar 2 json struct go

是否有可能:结构体中有一个字段,但在 Golang 中序列化/反序列化期间它有不同的名称?

例如,我有结构“坐标”。

type Coordinates struct {
  red int
}
Run Code Online (Sandbox Code Playgroud)

对于 JSON 的反序列化,需要这样的格式:

{
  "red":12
}
Run Code Online (Sandbox Code Playgroud)

但是当我序列化该结构时,结果应该是这样的:

{
  "r":12
}
Run Code Online (Sandbox Code Playgroud)

icz*_*cza 5

标准库不支持开箱即用,但使用自定义编组器/解组器您可以做任何您想做的事情。

例如:

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})
}
Run Code Online (Sandbox Code Playgroud)

(注意:必须导出结构体字段才能参与编组/解组过程。)

测试它:

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))
Run Code Online (Sandbox Code Playgroud)

输出(在Go Playground上尝试):

{"r":12}
Run Code Online (Sandbox Code Playgroud)