【问题标题】:Go-Gin binding data with one-to-many relationship具有一对多关系的 Go-Gin 绑定数据
【发布时间】:2021-11-06 07:25:12
【问题描述】:

我是 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,但是这样做的最佳做法是什么?

【问题讨论】:

    标签: go go-gorm go-gin


    【解决方案1】:

    您的负载与模型不匹配。在 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} ... }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-06
      • 2013-01-12
      • 1970-01-01
      • 1970-01-01
      • 2019-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多