gorm框架目前不支持Json类型的数据结构 http://gorm.book.jasperxu.com/callbacks.htmlhtml
如在Mysql中定义了以下的表结构sql
CREATE TABLE `report` ( `id` bigint(20) NOT NULL, `query_param` json NOT NULL, `create_by` varchar(50) DEFAULT NULL COMMENT '建立人', `create_date` timestamp NULL DEFAULT NULL COMMENT '建立时间', `update_by` varchar(50) DEFAULT NULL COMMENT '修改人', `update_date` timestamp NULL DEFAULT NULL COMMENT '修改时间', PRIMARY KEY (`id`), UNIQUE KEY `id_UNIQUE` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
解决办法是自定义一个JSON类型json
package models import ( "bytes" "errors" "database/sql/driver" ) type JSON []byte func (j JSON) Value() (driver.Value, error) { if j.IsNull() { return nil, nil } return string(j), nil } func (j *JSON) Scan(value interface{}) error { if value == nil { *j = nil return nil } s, ok := value.([]byte) if !ok { errors.New("Invalid Scan Source") } *j = append((*j)[0:0], s...) return nil } func (m JSON) MarshalJSON() ([]byte, error) { if m == nil { return []byte("null"), nil } return m, nil } func (m *JSON) UnmarshalJSON(data []byte) error { if m == nil { return errors.New("null point exception") } *m = append((*m)[0:0], data...) return nil } func (j JSON) IsNull() bool { return len(j) == 0 || string(j) == "null" } func (j JSON) Equals(j1 JSON) bool { return bytes.Equal([]byte(j), []byte(j1)) }
使用以下能够完美支持数据结构
type Report struct { ID int64 `json:"id"` QueryParam JSON `json:"queryParam"` CreateBy string `json:"createBy"` CreateDate time.Time `json:"createDate"` UpdateBy string `json:"updateBy"` UpdateDate time.Time `json:"updateDate"` }