You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Gin框架中将结构体作为单元素JSON数组返回?

解决Gin接口返回单条商品数据为数组格式的问题

你只需要把查询到的单个商品对象包装进数组里返回即可,有两种简洁的实现方式:

方式一:手动包装单个实例为数组

直接在返回JSON时,将单个Product实例放入切片中:

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": []*models.Products{&Product}})
    }
}

方式二:直接查询到数组变量中

如果希望从查询阶段就使用数组类型(即使仅返回一条数据),可以定义切片类型的变量,用Find方法查询:

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

两种方式都能让接口返回你期望的格式:

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

内容的提问来源于stack exchange,提问作者user19228159

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:12:32