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
謝謝。我修改了我的代碼,現在可以編譯和運行。 –