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 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类