无法将字符串解组到类型模型的Go struct字段Article.article_type中. [英] cannot unmarshal string into Go struct field Article.article_type of type models.ArticleType
本文介绍了无法将字符串解组到类型模型的Go struct字段Article.article_type中.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法将json字段 article_type
编组为golang结构 Article
.
I cannot unmarshal json field article_type
into golang struct Article
.
我遇到错误:
json:无法将字符串解组到类型模型的Go struct字段Article.article_type中.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":新闻"
解析为:Article.ArticleType.title =新闻"然后,我可以将具有标题为新闻"的文章类型的文章对象保存在数据库中.
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.
推荐答案
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
这篇关于无法将字符串解组到类型模型的Go struct字段Article.article_type中.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文