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

使用Gin与GORM开发Go后端时遇JSON序列化错误

问题分析与解决

问题原因

你直接将GORM的查询构建器对象(*gorm.DB)传给了gin的JSON序列化方法,这个对象包含大量内部方法和复杂类型(比如报错里的func() time.Time),JSON无法序列化这类函数类型,导致报错。

关键错误点:GORM的链式调用(Table/Select/Where)只是构建查询语句,并没有实际执行数据库查询,返回的不是查询结果,而是查询构建器本身。

修复方案

需要先执行查询,把聚合结果读取到普通基础类型(或可序列化类型)中,再返回给前端。

基础版本(假设sum结果不为空)

func GetCurrentStock(c *gin.Context) {
    var totalQty int64
    // 调用Scan方法执行查询,将sum结果写入totalQty
    err := initializers.DB.Table("dev.inventory_live").Debug().Select("sum(qtynos)").Where("NOT is_cut AND (remarks IS NULL OR remarks = '')").Scan(&totalQty).Error
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "error": err.Error(),
        })
        return
    }

    c.JSON(http.StatusOK, gin.H{
        "result": totalQty,
    })
}

处理NULL情况(无符合条件记录时sum返回NULL)

如果没有匹配的记录,sum(qtynos)会返回NULL,直接用int64接收会得到0,但如果需要明确区分“无数据”和“数量为0”,可以用sql.NullInt64:

import "database/sql"

func GetCurrentStock(c *gin.Context) {
    var totalQty sql.NullInt64
    err := initializers.DB.Table("dev.inventory_live").Debug().Select("sum(qtynos)").Where("NOT is_cut AND (remarks IS NULL OR remarks = '')").Scan(&totalQty).Error
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "error": err.Error(),
        })
        return
    }

    // 处理NULL:如果值无效(即数据库返回NULL),默认返回0,也可以返回其他标识
    result := totalQty.Int64
    if !totalQty.Valid {
        result = 0
    }

    c.JSON(http.StatusOK, gin.H{
        "result": result,
    })
}

内容的提问来源于stack exchange,提问作者fuzzy-memory

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 03:52:51