json - Go json.Unmarshal() 适用于单个实体但不适用于 slice

标签 json go slice

我将 Go 用于一个简单的 http 客户端。这是我正在解码的实体:

type Message struct {
    Id int64
    Timestamp int64
    Text string
    Author User
    LastEdited int64
}

type User struct {
    Id int64
    Name string
}

单个实体在 JSON 中看起来像这样:

{
    "text": "hello, can you hear me?",
    "timestamp": 1512964818565,
    "author": {
        "name": "andrea",
        "id": 3
    },
    "lastEdited": null,
    "id": 8
}

Go/json 解码单个实体没有问题:

var m Message

err = json.Unmarshal(body, &m)
if err != nil {
    printerr(err.Error())
}
println(m.Text)

但是,如果端点的返回是多个实体:

[
    {
        "text": "hello, can you hear me?",
        "timestamp": 1512964800981,
        "author": {
            "name": "eleven",
            "id": 4
        },
        "lastEdited": null,
        "id": 7
    }
]

然后我更改相应的 Unmarshall 以处理一片结构,Go 抛出错误:

var m []Message

err = json.Unmarshal(body, &m)
if err != nil {
    printerr(err.Error()) // unexpected end of JSON input
}

for i := 0; i < len(m); i++ {
    println(m[i].Text)
}

什么给了?

最佳答案

对我来说效果很好(在 playground 上尝试),您从哪里获取有效负载数据?听起来像是在截断它。

package main

import (
    "encoding/json"
    "fmt"
)

type Message struct {
    Id         int64
    Timestamp  int64
    Text       string
    Author     User
    LastEdited int64
}

type User struct {
    Id   int64
    Name string
}

func main() {
    body := []byte(`[
    {
        "text": "hello, can you hear me?",
        "timestamp": 1512964800981,
        "author": {
            "name": "eleven",
            "id": 4
        },
        "lastEdited": null,
        "id": 7
    }
]`)

    var m []Message

    err := json.Unmarshal(body, &m)
    if err != nil {
        fmt.Printf("error: %v") // unexpected end of JSON input
    }

    for i := 0; i < len(m); i++ {
        fmt.Println(m[i].Text)
    }
}

运行它会得到这个输出

hello, can you hear me?

关于json - Go json.Unmarshal() 适用于单个实体但不适用于 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47746431/

相关文章:

go - 解释一下执行时间差

go - 带有 select 语句的程序在 go 中逃脱死锁

map - 在 Go 模板中使用 map

python - Tensorflow : tf. argmax 和切片

python - ipyparallel 异常 : "You have attempted to connect to an IPython Cluster but no Controller could be found"

json - 如何使用 Swift 4.2 正确编码 JSON 响应?

css - 将大 Logo 堆叠到多个 CSS 上

python - 从 Python 中的 year-mm-dd 行中切出年份

javascript - ruby rails : Get json from controller in Javascript file

jquery - 将Grails从1.3.4升级到2.0.3后,将数据呈现为JSON无法正常工作