普通网友 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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?