我刚接触Golang和Gin框架,我已经创建了两个模型
type Product struct {
gorm.Model
Name string
Media []Media
}
type Media struct {
gorm.Model
URI string
ProductID uint
}我发送了一个POST请求来保存一个新产品,正文是:
{
"name": "Product1",
"media": [
"https://server.com/image1",
"https://server.com/image2",
"https://server.com/image3",
"https://server.com/video1",
"https://server.com/video2"
]
}我用下面的代码保存了一个新产品
product := Product{}
if err := context.ShouldBindJSON(product); err != nil { // <-- here the error
context.String(http.StatusBadRequest, fmt.Sprintf("err: %s", err.Error()))
return
}
tx := DB.Create(&product)
if tx.Error != nil {
context.String(http.StatusBadRequest, fmt.Sprintf("err: %s", tx.Error))
return
}返回的错误消息为
err: json: cannot unmarshal string into Go struct field Product.Media of type models.Media我知道ShouldBindJSON不能将media-string转换为media-object,但是这样做的最佳实践是什么?
发布于 2021-09-09 20:47:24
您的有效负载与模型不匹配。在JSON体中,media是一个字符串数组,而在模型中,它是一个具有两个字段和嵌入式gorm模型的结构。
如果您无法更改当前设置的任何内容,请在Media上实现UnmarshalJSON,并从原始字节设置URI字段。在相同的方法中,您也可以将ProductID初始化为某个值(如果需要)。
func (m *Media) UnmarshalJSON(b []byte) error {
m.URI = string(b)
return nil
}然后,绑定将按预期工作:
product := Product{}
// pass a pointer to product
if err := context.ShouldBindJSON(&product); err != nil {
// handle err ...
return
}
fmt.Println(product) // {Product1 [{"https://server.com/image1" 0} ... }https://stackoverflow.com/questions/69121393
复制相似问题