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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里