我有一个这样的结构:
package main
import (
"encoding/json"
"fmt"
)
type request struct {
Version string `json:"version"`
Operations map[string]operation `json:"operations"`
}
type operation struct {
Type string `json:"type"`
Width int `json:"width"`
Height int `json:"height"`
}
func main() {
jsonStr := "{\"version\": \"1.0\", \"operations\": {\"0\": {\"type\": \"type1\", \"width\": 100}, \"1\": {\"type\": \"type2\", \"height\": 200}}}"
req := request{
Version: "1.0",
}
err := json.Unmarshal([]byte(jsonStr), &req)
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Println(req)
}
}
我可以将 Version = "1.0"设置为其默认值,但是如何将默认值设置为宽度和高度?
最佳答案
编写一个解码函数来设置默认值:
func (o *operation) UnmarshalJSON(b []byte) error {
type xoperation operation
xo := &xoperation{Width: 500, Height: 500}
if err := json.Unmarshal(b, xo); err != nil {
return err
}
*o = operation(*xo)
return nil
}
我创建了一个 playground example对 JSON 进行修改以使其可运行。
关于json - 在 golang 中执行 json Unmarshal 时如何将默认值设置为映射值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35738111/