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条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效