【问题标题】:Decode JSON with Go用 Go 解码 JSON
【发布时间】:2018-05-05 21:58:50
【问题描述】:

我有一个这样的反应结构

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"`
}

我有一个函数使用一个 API,它应该返回 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
}

但不知何故,它无法显示我想要检索的对象的数组/切片,我根本没有得到任何数据。我错过了哪里?

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

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

这是原始回复

[
  {
    "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": ""
  }
]

【问题讨论】:

  • 不应该是json.NewDecoder(resp.Body).Decode(&result)吗?
  • 还是不行。
  • 失败是什么意思?输出是什么
  • 正如@Volker 指出的那样,您应该将指针传递给您的 getJson 函数:getJson("http://localhost:80/reactions", &reactList) 其余部分似乎还可以。
  • @MohamadNasir 这是一个例子play.golang.org/p/_PnNK64giE

标签: json go slice decode


【解决方案1】:

查看这个游乐场:https://play.golang.org/p/VjocUtiDRN

也许这就是你想要的。所以你应该让你的函数getJson(顺便说一句,getJSON 在 Golang 命名约定中是更好的名称)采用[]Reaction 参数,而不是interface{}。然后,您可以将类似数组的响应解组为 Reactions 的切片。

【讨论】:

    【解决方案2】:

    正如 cmets 中所指出的,您需要传递一个指向 getJson 的指针,以便它可以实际修改 slice 的内容。

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

    这是您所拥有的 https://play.golang.org/p/_PnNK64giE 的近似表示,只需看看您的情况有哪些地方没有到位。

    【讨论】:

      【解决方案3】:

      这里的主要错误是您传递的结果没有指针。应该是:

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

      【讨论】:

      • 这是不正确的,如果他将一个非指针传递给getJson 并将一个指针传递给Decode inside getJson,他仍然会得到一个getJson 返回后的空切片。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 2020-12-15
      • 2021-07-11
      • 1970-01-01
      • 2021-07-13
      相关资源
      最近更新 更多