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

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

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

问题

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

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

JSON响应如下:

{
    "data": {
        "ID": 1,
        ...
        "Feedback": null
    }
}

我想要的结果是:

{
    "data": [{
        "ID": 1,
        ...
        "Feedback": null
    }]
}
英文:

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

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

json response

{
    "data": {
        "ID": 1,
        ...
        "Feedback": null
    }
}

I want this:

{
    "data": [{
        "ID": 1,
        ...
        "Feedback": null
    }]
}

</details>


# 答案1
**得分**: 2

根据@mkopriva的建议,要将结构体作为单元素的JSON数组返回,可以将其包装在切片字面量中。

```go
var p models.Product
// ...
c.JSON(http.StatusOK, gin.H{"data": []models.Product{p}})

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

c.JSON(http.StatusOK, gin.H{"data": []interface{}{p}})
// 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.

var p models.Product
// ...
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

c.JSON(http.StatusOK, gin.H{&quot;data&quot;: []interface{}{p}})
// 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:

确定