RawMessage Scan&Value
json.RawMessage
以[]byte
形式存储json数据,但在父结构体marshal和unmarshal时不会重复序列化,仅仅将数据复制到新json字符串中
通过继承Scanner和Valuer实现结构体变量写入和读出数据库
1type JSON json.RawMessage
2
3func (j *JSON) Scan(value any) error {
4 bytes, ok := value.([]byte)
5 if !ok {
6 return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
7 }
8
9 result := json.RawMessage{}
10 err := json.Unmarshal(bytes, &result)
11 *j = JSON(result)
12 return err
13}
14
15func (j JSON) Value() (driver.Value, error) {
16 if len(j) == 0 {
17 return nil, nil
18 }
19 return json.RawMessage(j).MarshalJSON()
20}
map Scan&Value
1type AllowAppsModel map[string]bool
2
3func (a *AllowAppsModel) Scan(value any) error {
4 bytes, ok := value.([]byte)
5 if !ok {
6 return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
7 }
8 err := json.Unmarshal(bytes, a)
9 return err
10}
11
12func (a AllowAppsModel) Value() (driver.Value, error) {
13 return json.Marshal(a)
14}
除另有声明外,本博客文章均采用 知识共享 (Creative Commons) 署名 4.0 国际许可协议 进行许可。转载请注明原作者与文章出处。