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
相关产品推荐
相关产品推荐

