我有一个这样的结构:package mainimport ( "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" 设置为默认值,但如何将默认值设置为 Width 和 Height?
1 回答

撒科打诨
TA贡献1934条经验 获得超2个赞
编写一个解组函数来设置默认值:
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 示例,并修改了 JSON 以使其可运行。
- 1 回答
- 0 关注
- 347 浏览
添加回答
举报
0/150
提交
取消