duanaoou4105 2016-09-22 23:36
浏览 82

收到EOF紧急错误

I'm trying to decode a json I get. Here's an example json I get:

{"response":"1","number":"1234","id":nil}

Here's my struct:

type AutoGenerated struct {
Response string  `json:"response"`
Number     string  `json:"number"`
ID         interface{}     `json:"id"`
}

I use the decode function in encode/json. What Am I getting wrong? ID has the chance to be both a string or a nil value.

Here's me exact error incase it helps.

panic: EOF
  • 写回答

2条回答 默认 最新

  • douwa1304 2016-09-23 05:53
    关注

    The JSON string you put here is invalid. You can find this code sample for reference.

    If you're going to set the id field to nil, just don't put it in the JSON string.

    package main
    
    import (
        "encoding/json"
        "fmt"
        "io"
        "log"
        "strings"
    )
    
    type AutoGenerated struct {
        Response string      `json:"response"`
        Number   string      `json:"number"`
        ID       interface{} `json:"id"`
    }
    
    func main() {
        jsonStream := `
            { "response": "1", "number": "1234" }
            { "response": "1", "number": "1234", "id": "nil" }
        `
        decoder := json.NewDecoder(strings.NewReader(jsonStream))
        for {
            var m AutoGenerated
            if err := decoder.Decode(&m); err == io.EOF {
                break
            } else if err != nil {
                log.Fatal(err)
            }
            fmt.Println(m)
        }
    }
    

    The output of the program is:

    {1 1234 <nil>}
    {1 1234 nil}
    
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站