在 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:公告内容;"` // 这里是问题所在
// ... 其他字段
}
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
}