普通网友 2017-04-09 07:54
浏览 349
已采纳

无法将字符串解组到类型模型的Go struct字段Article.article_type中。

I cannot unmarshal json field article_type into golang struct Article.

I'm getting error:

json: cannot unmarshal string into Go struct field Article.article_type of type models.ArticleType

str := []byte(`[{"created_at":1486579331,"updated_at":1486579331,"article_type":"news"}]`)

type Article struct {
    ID            uint      `gorm:"primary_key"`
    CreatedAt     timestamp.Timestamp `json:"created_at"`
    UpdatedAt     timestamp.Timestamp `json:"updated_at"`

    ArticleType   ArticleType `json:"article_type"`
    ArticleTypeId uint        `gorm:"index" json:"-"`

type ArticleType struct {
    ID        uint      `gorm:"primary_key" json:"id"`
    CreatedAt timestamp.Timestamp `json:"created_at"`
    UpdatedAt timestamp.Timestamp `json:"updated_at"`
    Title     string    `gorm:"size:255" json:"title"`

    Articles  []Article `json:"articles"`
}

articles := []models.Article{}
if err := json.Unmarshal(str, &articles); err != nil {
    panic(err)
}

I wanted that "article_type":"news" would be parse as: Article.ArticleType.title = "news" And then I would can save article object which have article type with title "news" in database.

  • 写回答

1条回答 默认 最新

  • dpo60833 2017-04-09 09:46
    关注

    You can have your ArticleType implement the json.Unmarshaler interface by defining an UnmarshalJSON method on it:

    func (a *ArticleType) UnmarshalJSON(b []byte) error {
        a.Title = string(b)
        return nil
    }
    

    https://play.golang.org/p/k_UlghLxZI

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改