无法将字符串解组到 models.ArticleType 类型的 Go 结构字段 Article.article_type

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

我无法将 json 字段 article_type 解组为 golang 结构 Article

我遇到错误:

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)
}

我希望 "article_type":"news" 被解析为: Article.ArticleType.title = "news" 然后我可以在数据库中保存文章类型为 "news" 的文章对象。

您可以让 ArticleType 通过在其上定义 UnmarshalJSON 方法来实现 json.Unmarshaler 接口:

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

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