【问题标题】:cannot unmarshal string into Go struct field Article.article_type of type models.ArticleType无法将字符串解组到 Go 结构字段 Article.article_type 类型的 models.ArticleType
【发布时间】:2017-04-10 09:49:10
【问题描述】:

我无法将 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”的文章类型的文章对象。

【问题讨论】:

    标签: json go go-gorm


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-04
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-19
      • 2020-10-14
      相关资源
      最近更新 更多