1 回答
TA贡献2003条经验 获得超2个赞
您需要实现driver.Valuer和sql.Scanner接口以保存为 JSONB
接口,以便将driver.Valuer对象编组为数据库可以理解的 JSON 字节切片。
sql.Scanner接口,这样它将数据库中的 JSON 字节切片解组到结构字段中。
而对于 json Marshal 你需要转换map[int]float32成map[string]float32
type cusjsonb map[int]float32
// Returns the JSON-encoded representation
func (a cusjsonb) Value() (driver.Value, error) {
// Convert to map[string]float32 from map[int]float32
x := make(map[string]float32)
for k, v := range a {
x[strconv.FormatInt(int64(k), 10)] = v
}
// Marshal into json
return json.Marshal(x)
}
// Decodes a JSON-encoded value
func (a *cusjsonb) Scan(value interface{}) error {
b, ok := value.([]byte)
if !ok {
return errors.New("type assertion to []byte failed")
}
// Unmarshal from json to map[string]float32
x := make(map[string]float32)
if err := json.Unmarshal(b, &x); err != nil {
return err
}
// Convert to map[int]float32 from map[string]float32
*a = make(cusjsonb, len(x))
for k, v := range x {
if ki, err := strconv.ParseInt(k, 10, 32); err != nil {
return err
} else {
(*a)[int(ki)] = v
}
}
return nil
}
- 1 回答
- 0 关注
- 117 浏览
添加回答
举报
