dongzhi2014 2017-12-11 04:28
浏览 241
已采纳

Go json.Unmarshal()适用于单个实体,但不适用于切片

I'm using Go for a simple http client. Here's the entity I'm unmarshalling:

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

type User struct {
    Id int64
    Name string
}

A single entity looks like this in JSON:

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

Go/json has no problem unmarshalling the single entity:

var m Message

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

However, if the return of the endpoint is multiple entities:

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

And I change my corresponding Unmarshall to work on a slice of structs, Go throws an error:

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)
}

What gives?

  • 写回答

1条回答 默认 最新

  • duangouhui0446 2017-12-11 04:40
    关注

    Works fine for me (try it on playground), where are you getting the payload data from? sounds like that's truncating it.

    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)
        }
    }
    

    running it gives this output

    hello, can you hear me?
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题