dtvx3420 2017-11-22 08:33
浏览 68
已采纳

使用Go解码JSON

I have a reaction struct like this

type Reaction struct {
    Id           uint   `json:"id" form:"id"`
    ReactionType uint   `json:"reactionType" form:"reactionType"`
    PostId       uint   `json:"postId" form:"postId"`
    ReactorId    uint   `json:"reactorId" form:"reactorId"`
    CreatedAt    string `json:"createdAt" form:"createdAt"`
    UpdatedAt    string `json:"updatedAt" form:"createdAt"`
}

And I have a function that consumes an API that should return a slice of Reaction

var myClient = &http.Client{Timeout: 7 * time.Second}

func getJson(url string, result interface{}) error {
  req, _ := http.NewRequest("GET", url, nil)
  resp, err := myClient.Do(req)

  if err != nil {
     return fmt.Errorf("cannot fetch URL %q: %v", url, err)
  }
  defer resp.Body.Close()

  if resp.StatusCode != http.StatusOK {
    return fmt.Errorf("unexpected http GET status: %s", resp.Status)
  }

  err = json.NewDecoder(resp.Body).Decode(result)
  if err != nil {
     return fmt.Errorf("cannot decode JSON: %v", err)
  }
  return nil
}

But somehow it failed to display the array/slice of objects that I want to retrieve, I got no data at all. Where did I miss?

func main(){
   ..
   ..
   var reactList []Reaction
   getJson("http://localhost:80/reactions", reactList)

   for _, r := range reactList {
        fmt.Print(r.ReactionType)
    }
}

and this is the original responses

[
  {
    "id": 55,
    "reactionType": 5,
    "reactorId": 2,
    "postId": 4,
    "createdAt": "2017-11-18 14:23:29",
    "updatedAt": ""
  },
  {
    "id": 56,
    "reactionType": 5,
    "reactorId": 3,
    "postId": 4,
    "createdAt": "2017-11-18 14:23:42",
    "updatedAt": ""
  },
  {
    "id": 57,
    "reactionType": 4,
    "reactorId": 4,
    "postId": 4,
    "createdAt": "2017-11-18 14:23:56",
    "updatedAt": ""
  }
]
  • 写回答

3条回答 默认 最新

  • dongtuoji5396 2017-11-22 09:08
    关注

    As pointed out in the comments you need to pass a pointer to getJson so that it can actually modify the contents of slice.

    getJson("http://localhost:80/reactions", &reactList)
    

    This is a close representation of what you have https://play.golang.org/p/_PnNK64giE, just see where things aren't in place in your case.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化