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 關注
- 94 瀏覽
添加回答
舉報