普通网友 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

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

报告相同问题?

悬赏问题

  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码