doulanli6146 2017-11-22 11:14
浏览 153
已采纳

json错误,无法将对象解组为Go值

I have this JSON data:

{
"InfoA" : [256,256,20000],
"InfoB" : [256,512,15000],
"InfoC" : [208,512,20000],
"DEFAULT" : [256,256,20000]
}

With JSON-to-Go, I get this Go type definition:

type AutoGenerated struct {
    InfoA   []int `json:"InfoA"`
    InfoB   []int `json:"InfoB"`
    InfoC   []int `json:"InfoC"`
    DEFAULT []int `json:"DEFAULT"`
}

With this code (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, &params)
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }
}

I get error json: cannot unmarshal object into Go value of type []main.paramsInfo

I don't understand why. Can you help me?

  • 写回答

2条回答 默认 最新

  • duandiao3961 2017-11-22 11:17
    关注

    The JSON source is a single object, yet you try to unmarshal it into a slice. Change the type of params to paramsInfo (non-slice):

    var params paramsInfo
    err := json.Unmarshal(rawJSON, &params)
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }
    fmt.Printf("%+v", params)
    

    And with that the output (try it on the Go Playground):

    {InfoA:[256 256 20000] InfoB:[256 512 15000] InfoC:[208 512 20000]
        DEFAULT:[256 256 20000]}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办