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

GORM读取PostgreSQL的interface{}类型JSONB字段报错及解决问询

错误原因

你定义的customJson是接口类型(interface{}),Go语言不允许为接口类型直接定义方法,这就是报错invalid receiver type customJson (pointer or interface type)的核心原因。


解决方案

方案1:用自定义类型包裹interface{}实现接口

定义一个底层为interface{}的自定义类型,为它实现sql.Scanner和driver.Valuer接口,替代原生interface{}作为字段类型:

import (
    "database/sql/driver"
    "encoding/json"
    "errors"
    "fmt"
)

// 自定义类型,底层是interface{}
type CustomJSON interface{}

// 为自定义类型的指针实现Scan方法
func (j *CustomJSON) Scan(value interface{}) error {
    bytes, ok := value.([]byte)
    if !ok {
        return errors.New(fmt.Sprintf("无法解析JSONB值: %v", value))
    }
    return json.Unmarshal(bytes, j)
}

// 为自定义类型实现Value方法
func (j CustomJSON) Value() (driver.Value, error) {
    return json.Marshal(j)
}

// 修改FlowTransaction的ReconData字段类型
type FlowTransaction struct {
    gorm.Model
    Name                          string
    PartnerTransactionReferenceId string
    ReconData                     CustomJSON `gorm:"type:jsonb"` // 使用自定义类型
    DestinationAccountNumber      *string
    DestinationIfsc               *string
    Amount                        uint64
    PartnerId                     uint
    FlowId                        uint
    SelfSettle                    bool
    IsSandbox                     bool
}

方案2:用具体结构体替代interface{}(推荐)

如果ReconData的结构是固定的,直接用具体结构体作为字段类型,GORM会自动处理JSONB的序列化/反序列化,无需手动实现接口,类型更安全:

// 定义ReconData的具体结构
type ReconData struct {
    TransactionID string `json:"transaction_id"`
    Status        string `json:"status"`
    // 补充你的实际字段
}

type FlowTransaction struct {
    gorm.Model
    Name                          string
    PartnerTransactionReferenceId string
    ReconData                     ReconData `gorm:"type:jsonb"` // 使用具体结构体
    DestinationAccountNumber      *string
    DestinationIfsc               *string
    Amount                        uint64
    PartnerId                     uint
    FlowId                        uint
    SelfSettle                    bool
    IsSandbox                     bool
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:20:59