[英]gorm: json of json not work
Sample: 样品:
{
"id": 1
"data": {"1": 2}
}
Struct definition: 结构定义:
type Item struct {
id int `json:"id"`
data interface{} `json:"data"`
}
I need to parse the payload from a http post, so I used interface{}
for data
, json.Unmarshal()
is successful, but gorm produces error while calling db.Create(item)
: 我需要从http帖子中解析有效负载,因此我将interface{}
用于data
, json.Unmarshal()
成功,但是gorm在调用db.Create(item)
产生错误:
(sql: converting Exec argument #5's type: unsupported type map[string]interface {}, a map)
Instead, I change from interface{}
to string
, calling json.Unmarshal()
to parse json POST payload produces error. 相反,我从interface{}
更改为string
,调用json.Unmarshal()
解析JSON POST有效负载会产生错误。
unmarshal type error: expected=string, got=object
Basically, one requires interface{}
, one requires string
. 基本上,一个需要interface{}
,一个需要string
。
Anyone encountered this? 有人遇到过这个吗?
The solution is defining a custom type that implements sql.Valuer
, sql.Scanner
, json.Marshaler
and json.Unmarshaler
interfaces. 解决方案是定义一个自定义类型,该类型实现sql.Valuer
, sql.Scanner
, json.Marshaler
和json.Unmarshaler
接口。 Sample of my implementation: 我的实现示例:
type Data string
func (t *Data) MarshalJSON() ([]byte, error) {
return []byte(*t), nil
}
func (t *Data) UnmarshalJSON(data []byte) error {
*t = Data(data)
return nil
}
func (t Data) Value() (driver.Value, error) {
return string(t), nil
}
func (t *Data) Scan(src interface{}) error {
s, ok := src.([]byte)
if !ok {
return nil
}
*t = Data(s)
return nil
}
// Data implements the below interfaces to satisfy both
// json parser and sql parser
var _ json.Marshaler = (*Data)(nil)
var _ json.Unmarshaler = (*Data)(nil)
var _ sql.Scanner = (*Data)(nil)
var _ driver.Valuer = (*Data)(nil)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.