英文:
How to insert json field into mysql
问题
我正在尝试将一个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,
}
当尝试插入上述entry模型时,我在插入casting类型时遇到以下错误。
converting argument type: unsupported type model.StringInterfaceMap, a map
英文:
I am trying to insert a json field into mysql. Its giving an error.Need your help here.
My sample code class
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,
}
When trying to insert the above entry model am getting the folowing error in inserting casting type.
converting argument type: unsupported type model.StringInterfaceMap, a map
答案1
得分: 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
}
英文:
Have the custom map type implement the driver.Valuer
interface, e.g.
func (m StringInterfaceMap) Value() (driver.Value, error) {
return json.Marshal(m)
}
And if you want to be able to also retrieve the json from the db you can implement the sql.Scanner
interface, e.g.
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论