gorm db.find(&users)在Golang中使用gin将其转换为JSON。

huangapple go评论70阅读模式
英文:

gorm db.find(&users) to json with gin in golang

问题

这是我的GET方法,问题是我在JSON中只得到一个用户,而实际上我的数据库中有3个用户。

func GetUsers(c *gin.Context) {
    var users = db.Find(&models.Person{})
    c.JSON(200, users)
}
英文:

This is my GET Method the problem is that all i get in the json is one user instead there are 3 users in my database.

func GetUsers(c *gin.Context) {

var users = db.Find(&models.Person{})
c.JSON(200, users)
}

答案1

得分: 7

尝试这样写:

func GetUsers(c *gin.Context) {
    users := []models.Person{}
    db.Find(&users)
    c.JSON(200, &users)
}

这段代码使用了Gin框架,通过调用GetUsers函数来获取用户信息,并将结果以JSON格式返回给客户端。在函数内部,首先定义了一个空的users切片,然后使用db.Find方法从数据库中查询用户信息并将结果赋值给users切片。最后,使用c.JSON方法将users切片以JSON格式返回给客户端,HTTP状态码为200。

英文:

Try this:

func GetUsers(c *gin.Context) {
 users := []models.Person{}
 db.Find(&users)
 c.JSON(200, &users)
}

huangapple
  • 本文由 发表于 2017年1月3日 04:58:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/41433207.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定