3
我有这样的结构:如何将默认值设置为映射值时执行json Unmarshal golang?
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)
}
}
我可以设置版本=“1.0”为默认值,但我怎么能默认值设置为宽度和高度?
你的'json'看起来不是有效的,'Unmarshal'返回一个err,所以在'Unmarshal'前面放一个'err:=',我相信你可以调试它你自己,但现在我不明白你的问题,你正在使用'float'来代替'int32',你的'json'似乎不是有效的。 – Datsik
谢谢。我修改了我的代码,现在可以编译和运行。 –