[已解决] gorm 读取json结构数据时,读取不到值
想了解一下gorm对于json类型字段的应用,定义了一个Media 结构体,预设info为一个json格式的字段,数据库已有数据,添加和编辑可以按正常流程对info字段操作,但是读取列表时无法正常显示
定义 Media 结构体
type Media struct {
// id
BaseModel
Title string `gorm:"not null;varchar(100);default:'';comment:标题;" json:"title"`
Url string `gorm:"not null;varchar(255);default:'';comment:链接;" json:"url"`
GroupId uint64 `gorm:"not null;default:0;comment:分组id;" json:"group_id"`
MediaType string `gorm:"not null;varchar(100);comment:媒体类型;" json:"media_type"`
ContentType string `gorm:"not null;varchar(100);comment:标头类型" json:"content_type"`
Size int64 `gorm:"not null;default:0;comment:大小;" json:"size"`
Info MediaInfo `gorm:"type:json;comment:详情;" json:"info"`
// 时间
CommonTimestampsField
}
定义MediaInfo
type MediaInfo struct {
Width int64 `json:"width"`
Height int64 `json:"height"`
Duration int64 `json:"duration"`
}
// Value 存储数据的时候转换为字符串
func (i MediaInfo) Value() (driver.Value, error) {
return json.Marshal(i)
}
// Scan 读取数据的时候转换为json
func (i MediaInfo) Scan(value interface{}) error {
if val, ok := value.([]byte); ok {
r := json.Unmarshal(val, &i)
return r
}
return nil
//return json.Unmarshal(value.([]byte), &i)
}
读取数据库中的数据
var media models.Media
db.Model(models.Media{}).First(&media)
a2, _ := json.Marshal(media)
fmt.Println(string(a2))
输出结果
{
"id":1,
"title":"01.png",
"url":"http://120.0.0.1:3004/static/others/image/EZ7QVBD7VGJbK0b6.png",
"group_id":0,
"media_type":"image",
"content_type":"image/png",
"size":68942,
// 这里应该是{"width":500,"height":500,"duration":0}
"info":{"width":0,"height":0,"duration":0},
"created_at":"2023-06-25 15:36:03",
"updated_at":"2023-06-25 15:36:03",
"deleted_at":null
}
info字段并没有读取到正确的值,但是在scan中打印出来的数据是能够读取到正常数据的,实在想不通为什么info字段获取不到数据库中的数据,请大神指教