如何在Gin中将结构体作为一个元素的JSON数组返回?

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

How to return a struct as a one-element JSON array in Gin?

问题

我有一个根据产品ID返回产品的函数,但问题是它不以数据数组的形式返回。

  1. func GetProductsById(c *gin.Context) {
  2. var Product models.Products
  3. if err := config.DB.Where("id=?", c.Query("prod_id")).First(&Product).Error; err != nil {
  4. c.JSON(http.StatusInternalServerError, err.Error())
  5. } else {
  6. c.JSON(http.StatusOK, gin.H{"data": &Product})
  7. }
  8. }

JSON响应如下:

  1. {
  2. "data": {
  3. "ID": 1,
  4. ...
  5. "Feedback": null
  6. }
  7. }

我想要的结果是:

  1. {
  2. "data": [{
  3. "ID": 1,
  4. ...
  5. "Feedback": null
  6. }]
  7. }
英文:

I have a function that returns a product by its ID, but the problem is that it does not return it as a data array

  1. func GetProductsById(c *gin.Context) {
  2. var Product models.Products
  3. if err := config.DB.Where("id=?", c.Query("prod_id")).First(&Product).Error; err != nil {
  4. c.JSON(http.StatusInternalServerError, err.Error())
  5. } else {
  6. c.JSON(http.StatusOK, gin.H{"data": &Product})
  7. }
  8. }

json response

  1. {
  2. "data": {
  3. "ID": 1,
  4. ...
  5. "Feedback": null
  6. }
  7. }

I want this:

  1. {
  2. "data": [{
  3. "ID": 1,
  4. ...
  5. "Feedback": null
  6. }]
  7. }
  8. </details>
  9. # 答案1
  10. **得分**: 2
  11. 根据@mkopriva的建议,要将结构体作为单元素的JSON数组返回,可以将其包装在切片字面量中。
  12. ```go
  13. var p models.Product
  14. // ...
  15. c.JSON(http.StatusOK, gin.H{"data": []models.Product{p}})

如果你不想为切片项指定特定的类型,可以使用[]interface{}或从Go 1.18开始使用[]any

  1. c.JSON(http.StatusOK, gin.H{"data": []interface{}{p}})
  2. // c.JSON(http.StatusOK, gin.H{"data": []any{p}})
英文:

As suggested by @mkopriva, to easily return a struct as a single-element JSON array, wrap it in a slice literal.

  1. var p models.Product
  2. // ...
  3. c.JSON(http.StatusOK, gin.H{&quot;data&quot;: []models.Product{p}})

If you don't want to specify a particular type for the slice items, you can use []interface{}, or []any starting from Go 1.18

  1. c.JSON(http.StatusOK, gin.H{&quot;data&quot;: []interface{}{p}})
  2. // c.JSON(http.StatusOK, gin.H{&quot;data&quot;: []any{p}})

huangapple
  • 本文由 发表于 2022年7月16日 17:01:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/73002873.html
匿名

发表评论

匿名网友

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

确定