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}
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?