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

3

我有一个这样的结构体:

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”设置为其默认值,但是如何将默认值设置为Width和Height?


1
你的 json 似乎不是有效的,Unmarshal 返回一个错误,所以在那个 Unmarshal 前面抛出一个 err :=,我相信你能自己调试它,但现在我真的不太理解你的问题,你正在使用一个 float 替代一个 int32,而且你的 json 似乎不是有效的。 - Datsik
谢谢。我修改了我的代码,现在可以编译和运行了。 - windy_zhh
1个回答

5
编写一个反序列化函数来设置默认值:
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
}

我创建了一个可运行的示例,并对JSON进行了修改。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接