json:无法将数组解码为 main.Data 类型的 Go 值

标签 json go

Json 是 -

    {
"apiAddr":"abc",
"data":
    [
        {
        "key":"uid1",
        "name":"test",
        "commandList":["dummy cmd"],
        "frequency":"1",
        "deviceList":["dev1"],
        "lastUpdatedBy": "user",
        "status":"Do something"
        }
]

解码的代码是 -

   type Data struct {
    APIAddr string             `json:"apiAddr"`
    Data    []Template         `json:"data"`
   }

    type Template struct {
   Key           string   `json:"key"`
   Name          string   `json:"name"`
   CommandList   []string `json:"commandList"`
   Frequency     string   `json:"frequency"`
   DeviceList    []string `json:"deviceList"`
   LastUpdatedBy string   `json:"lastUpdatedBy"`
   Status        string   `json:"status"`
}
   raw, err := ioutil.ReadFile(*testFile)
      if err != nil {
        return
    }
    var testTemplates Data
    err = json.Unmarshal(raw, &testTemplates)
    if err != nil {
        return
    }

其中 testFile 是 json 文件。 我收到这个错误

json: cannot unmarshal array into Go value of type main.Data.

查看stackoverflow中的现有问题,看起来我做的很好。有人吗?

最佳答案

做了一些修改,Unmarshaling 工作得很好。

package main

import (
    "encoding/json"
    "fmt"
)

var raw = `   {
"apiAddr":"abc",
"data":
    [
        {
        "key":"uid1",
        "name":"test",
        "commandList":["dummy cmd"],
        "frequency":"1",
        "deviceList":["dev1"],
        "lastUpdatedBy": "user",
        "status":"Do something"
        }
]
}`

func main() {
    var testTemplates Data
    err := json.Unmarshal([]byte(raw), &testTemplates)
    if err != nil {
        return
    }
    fmt.Println("Hello, playground", testTemplates)
}

type Data struct {
    APIAddr string     `json:"apiAddr"`
    Data    []Template `json:"data"`
}

type Template struct {
    Key           string   `json:"key"`
    Name          string   `json:"name"`
    CommandList   []string `json:"commandList"`
    Frequency     string   `json:"frequency"`
    DeviceList    []string `json:"deviceList"`
    LastUpdatedBy string   `json:"lastUpdatedBy"`
    Status        string   `json:"status"`
}

您也可以在 Playground 中运行它:https://play.golang.org/p/TSmUnFYO97-

关于json:无法将数组解码为 main.Data 类型的 Go 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50364487/

相关文章:

java - REST/JSON : How to generate sample requests ? 如何暴露API?

java - Json/Jackson 命名约定

json - 如何使用 golang 将事件字段更改为非事件状态以保持字段值不变?

go - 为什么下面的 Go 程序需要函数的名称是 String() 而不是其他任何东西?

object - Golang - 通过接口(interface)通过 2 步解码/重建对象

go - Go 中的 Tensorflow 服务

python - Pandas `read_json` 函数将字符串转换为 DateTime 对象,即使指定了 `convert_dates=False` attr

php - 当 php mysql_query 在 phpmyadmin 中工作时,某些列的空白结果

javascript - 如何访问 JSON 对象属性

go - 从调用另一个 goroutine 的 goroutine 返回