我有以下JSON数据:
{ "InfoA" : [256,256,20000], "InfoB" : [256,512,15000], "InfoC" : [208,512,20000], "DEFAULT" : [256,256,20000] }
使用JSON-to-Go,我得到以下Go类型定义:
type AutoGenerated struct { InfoA []int `json:"InfoA"` InfoB []int `json:"InfoB"` InfoC []int `json:"InfoC"` DEFAULT []int `json:"DEFAULT"` }
使用此代码(play.golang.org)
package main import ( "encoding/json" "fmt" "os" "strings" ) func main() { type paramsInfo struct { InfoA []int `json:"InfoA"` InfoB []int `json:"InfoB"` InfoC []int `json:"InfoC"` DEFAULT []int `json:"DEFAULT"` } rawJSON := []byte(`{ "InfoA" : [256,256,20000], "InfoB" : [256,512,15000], "InfoC" : [208,512,20000], "DEFAULT" : [256,256,20000] }`) var params []paramsInfo err := json.Unmarshal(rawJSON, ¶ms) if err != nil { fmt.Println(err.Error()) os.Exit(1) } }
我得到错误 json: cannot unmarshal object into Go value of type []main.paramsInfo
json: cannot unmarshal object into Go value of type []main.paramsInfo
我不明白为什么。你能帮助我吗?
JSON源是单个对象,但是您尝试将其解组为切片。将类型更改params为paramsInfo(非切片):
params
paramsInfo
var params paramsInfo err := json.Unmarshal(rawJSON, ¶ms) if err != nil { fmt.Println(err.Error()) os.Exit(1) } fmt.Printf("%+v", params)
然后输出(在Go Playground上尝试):
{InfoA:[256 256 20000] InfoB:[256 512 15000] InfoC:[208 512 20000] DEFAULT:[256 256 20000]}