[英]json error, cannot unmarshal object into Go value
我有這個 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 源是單個對象,但您嘗試將其解組為一個切片。 將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]}
您正在解碼單個 JSON 對象,但您正試圖將其放入[]paramsInfo
切片中。
當您解碼 JSON 對象數組時,它工作正常:
rawJSON := []byte(`[{
"InfoA" : [256,256,20000],
"InfoB" : [256,512,15000],
"InfoC" : [208,512,20000],
"DEFAULT" : [256,256,20000]
}]`)
(注意對象周圍的方括號)
順便說一句,在處理錯誤的if
分支中,您不需要調用err.Error()
來獲取錯誤字符串; fmt.Println(err)
就足夠了,像這樣使用它實際上是一個 Go 習慣用法。 fmt.Print*
的實現負責處理error
類型(例如與print
相反)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.