postgresql model Jsonb格式存储 gorm2.0

type JSON json.RawMessage

// Scan scan value into Jsonb, implements sql.Scanner interface
func (j *JSON) Scan(value interface{}) error {
    bytes, ok := value.([]byte)
    if !ok {
        return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
    }

    result := json.RawMessage{}
    err := json.Unmarshal(bytes, &result)
    *j = JSON(result)
    return err
}

// Value return json value, implement driver.Valuer interface
func (j JSON) Value() (driver.Value, error) {
    if len(j) == 0 {
        return nil, nil
    }
    return json.RawMessage(j).MarshalJSON()
}

func (JSON) GormDBDataType(db *gorm.DB, field *schema.Field) string {
    // use field.Tag, field.TagSettings gets field's tags
    // checkout https://github.com/go-gorm/gorm/blob/master/schema/field.go for all options

    // returns different database type based on driver name
    switch db.Dialector.Name() {
    case "mysql", "sqlite":
        return "JSON"
    case "postgres":
        return "JSONB"
    }
    return ""
}

// convert map[string]interface{} to JSON
func MapToJSON(m *map[string]interface{}) (JSON, error) {
    if m == nil {
        return nil, errors.New("map is nil")
    }
    bytes, err := json.Marshal(*m)
    if err != nil {
        return nil, err
    }
    return bytes, nil
}

// convert JSON to map[string]interface{}
func JSONToMap(j JSON) map[string]interface{} {
    if j == nil {
        return nil
    }
    var m map[string]interface{}
    err := json.Unmarshal(j, &m)
    if err != nil {
        return nil
    }
    return m
}

// convert JSON to json.RawMessage
func JSONToRawMessage(j JSON) json.RawMessage {
    if j == nil {
        return nil
    }
    return json.RawMessage(j)
}

//结构体引用

type XXX struct {
Data         JSON `json:"data"`          //数据
}

posted @ 2022-03-29 14:22  hubb  阅读(527)  评论(0编辑  收藏  举报