【问题标题】:How to insert json field into mysql如何将json字段插入mysql
【发布时间】:2022-01-18 18:19:07
【问题描述】:

我正在尝试将 json 字段插入 mysql。它给出了一个错误。在这里需要你的帮助。

我的示例代码类

type StringInterfaceMap map[string]interface{}

type Movie struct {
    Id           int
    Name         string
    Casting      StringInterfaceMap
    Language     string
    Release_date time.Time
    Rating       float32
    IsAbove18    bool
}

func buildBrowserData() map[string]interface{} {
    return map[string]interface{}{
        "Actor": "Rajinikanth", "Music": "Deva",
        "resolution": struct {
            X int json:"x"
            Y int json:"y"
        }{1920, 1080},
    }
}
entry := model.Movie{
        Id:           6,
        Name:         ctx.QueryParam("Name"),
        Casting:      buildBrowserData(),
        Language:     ctx.QueryParam("Language"),
        Release_date: ctx.QueryParam("Release_date"),
        Rating:       1,
        IsAbove18:    true,
    }

在尝试插入上述入口模型时,在插入铸造类型时出现以下错误。 转换参数类型:不支持的类型 model.StringInterfaceMap, a map

【问题讨论】:

    标签: mysql go


    【解决方案1】:

    让自定义地图类型实现driver.Valuer 接口,例如

    func (m StringInterfaceMap) Value() (driver.Value, error) {
        return json.Marshal(m)
    }
    

    如果您还希望能够从数据库中检索 json,您可以实现 sql.Scanner 接口,例如

    func (m *StringInterfaceMap) Scan(src interface{}) error {
        switch data := src.(type) {
        case []byte:
            return json.Unmarshal(data, m)
        case string:
            return json.Unmarshal([]byte(data), m)
        default:
            return fmt.Errorf("unsupported type: %T", src)
        }
        return nil
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-11
      • 2016-06-30
      • 2012-07-22
      • 2021-11-29
      • 2014-02-26
      • 2016-10-10
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      相关资源
      最近更新 更多