douzhan8395 2017-09-19 19:55
浏览 43
已采纳

如何使用goreq将json转换为struct?

Using Go I'm trying to get some json from a server for which I'm using the goreq library. When I print out the resulting string as follows:

s, _ := res.Body.ToString()
fmt.Println(s)

I get a correct json string:

{"success":true,"testnet":false,"message":"","result":{"btc":4014.16,"edp":4014.16},"msIn":1505820331492,"msOut":1505820331492}

So using this json-to-go webservice I converted this json message to a struct:

type Index struct {
    Success bool   `json:"success"`
    Testnet bool   `json:"testnet"`
    Message string `json:"message"`
    Result  struct {
        Btc float64 `json:"btc"`
        Edp float64 `json:"edp"`
    } `json:"result"`
    MsIn  int64 `json:"msIn"`
    MsOut int64 `json:"msOut"`
}

and I use that as follows (implementation of FromJsonTo() here):

var item Index
res.Body.FromJsonTo(&item)
fmt.Println(item)

This just prints out the nulled Index struct though (while the json str is still the same):

{false false  {0 0} 0 0}

Any idea what I might be doing wrong here?

  • 写回答

1条回答 默认 最新

  • douzhai7873 2017-09-20 05:43
    关注

    By calling res.Body.ToString() you read the whole body of the response. Next, when you call res.Body.FromJsonTo(), body is empty and therefore EOF error is returned. Removing ToString() from your code should help.

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

报告相同问题?

悬赏问题

  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来