Matuto的博客

Matuto的博客

马图图

岁月变迁何必不悔,尘世喧嚣怎能无愧。

25 文章数
1 评论数
Go

Go 中 []byte 类型的序列化

马图图
2024-12-23 / 0 评论 / 82 阅读 / 0 点赞

Go 中 []byte 类型的序列化问题

在 Go中 []byte 类型在 JSON 序列化时会被默认转换为 Base64 字符串。

type Notice struct {
    Id            string     `gorm:"column:id;comment:公告ID;"`
    NoticeTitle   string     `gorm:"column:notice_title;comment:公告标题;"`
    NoticeType    string     `gorm:"column:notice_type;comment:公告类型(1通知 2公告);"`
    NoticeContent []byte     `gorm:"column:notice_content;comment:公告内容;"` // 这里是问题所在
    // ... 其他字段
}

两种解决方案

  1. 修改模型定义,将 []byte 改为 string
  2. 添加自定义的 MarshalJSON 方法
type Notice struct {
    Id            string     `json:"id" gorm:"column:id;comment:公告ID;"`
    NoticeTitle   string     `json:"noticeTitle" gorm:"column:notice_title;comment:公告标题;"`
    NoticeType    string     `json:"noticeType" gorm:"column:notice_type;comment:公告类型(1通知 2公告);"`
    NoticeContent string     `json:"noticeContent" gorm:"column:notice_content;comment:公告内容;type:text"`
    Status        string     `json:"status" gorm:"column:status;comment:公告状态(0正常 1关闭);"`
    CreateBy      string     `json:"createBy" gorm:"column:create_by;comment:创建者;"`
    CreateTime    *time.Time `json:"createTime" gorm:"column:create_time;comment:创建时间;"`
    UpdateBy      string     `json:"updateBy" gorm:"column:update_by;comment:更新者;"`
    UpdateTime    *time.Time `json:"updateTime" gorm:"column:update_time;comment:更新时间;"`
    Remark        string     `json:"remark" gorm:"column:remark;comment:备注;"`
}
// MarshalJSON 自定义JSON序列化方法
func (n Notice) MarshalJSON() ([]byte, error) {
    type Alias Notice // 创建别名以避免递归
    return json.Marshal(&struct {
        Alias
        NoticeContent string `json:"noticeContent"`
    }{
        Alias:         Alias(n),
        NoticeContent: string(n.NoticeContent), // 转换为字符串
    })
}

// UnmarshalJSON 自定义JSON反序列化方法
func (n *Notice) UnmarshalJSON(data []byte) error {
    type Alias Notice
    aux := &struct {
        *Alias
        NoticeContent string `json:"noticeContent"`
    }{
        Alias: (*Alias)(n),
    }
    if err := json.Unmarshal(data, &aux); err != nil {
        return err
    }
    n.NoticeContent = []byte(aux.NoticeContent) // 转换回[]byte
    return nil
}
下一篇
评论
来首音乐
最新回复
光阴似箭
今日已经过去小时
这周已经过去
本月已经过去
今年已经过去个月
文章目录
每日一句