我有这个JSON数据:
{
"InfoA" : [256,256,20000],
"InfoB" : [256,512,15000],
"InfoC" : [208,512,20000],
"DEFAULT" : [256,256,20000]
}
Run Code Online (Sandbox Code Playgroud)
使用JSON-to-Go,我得到了这个Go类型定义:
type AutoGenerated struct {
InfoA []int `json:"InfoA"`
InfoB []int `json:"InfoB"`
InfoC []int `json:"InfoC"`
DEFAULT []int `json:"DEFAULT"`
}
Run Code Online (Sandbox Code Playgroud)
使用此代码(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)
}
}
Run Code Online (Sandbox Code Playgroud)
我收到错误 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)
Run Code Online (Sandbox Code Playgroud)
然后输出(在Go Playground上试试):
{InfoA:[256 256 20000] InfoB:[256 512 15000] InfoC:[208 512 20000]
DEFAULT:[256 256 20000]}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2954 次 |
最近记录: |