【发布时间】: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