为了账号安全,请及时绑定邮箱和手机立即绑定

在golang中执行json Unmarshal时如何将默认值设置为映射值?

在golang中执行json Unmarshal时如何将默认值设置为映射值?

Go
炎炎设计 2021-12-20 10:52:24
我有一个这样的结构: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 以使其可运行。


查看完整回答
反对 回复 2021-12-20
  • 1 回答
  • 0 关注
  • 347 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号