[已解决] gorm 读取json结构数据时,读取不到值

想了解一下gorm对于json类型字段的应用,定义了一个Media 结构体,预设info为一个json格式的字段,数据库已有数据,添加和编辑可以按正常流程对info字段操作,但是读取列表时无法正常显示

gorm 使用读取json结构数据时,读取不到值

定义 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字段获取不到数据库中的数据,请大神指教

Evn
最佳答案
func (i MediaInfo) Scan(value interface{}) error {
换成 下面的试下
func (i *MediaInfo) Scan(value interface{}) error {
1年前 评论
Evn_ (楼主) 1年前
讨论数量: 7

你的结构体:

type MediaInfo struct {
    Width    int64 `json:"width"`
    Height   int64 `json:"height"`
    Duration int64 `json:"duration"`
}

建议打上gorm约束:

`gorm:"width"`

还有这里:

db.Model(models.Media{}).First(&media)
//建议改成:
db.Model(&models.Media{}).First(&media)
1年前 评论
Evn_ (楼主) 1年前
ice_moss (作者) 1年前
func (i MediaInfo) Scan(value interface{}) error {
换成 下面的试下
func (i *MediaInfo) Scan(value interface{}) error {
1年前 评论
Evn_ (楼主) 1年前

gorm:"serializer:json" 了解一下

1年前 评论

你是不是李冰啊,怎么开始学go了,要不要这么卷啊

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!