英文:
cannot unmarshal string into Go struct field Article.article_type of type models.ArticleType
问题
我无法将JSON字段article_type
解组为Golang结构Article
。
我得到了以下错误:
json: 无法将字符串解组为类型为models.ArticleType的Go结构字段Article.article_type
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"的文章类型的文章对象保存在数据库中。
英文:
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
得分: 2
你可以让你的ArticleType
实现json.Unmarshaler接口,通过在其上定义一个UnmarshalJSON
方法:
func (a *ArticleType) UnmarshalJSON(b []byte) error {
a.Title = string(b)
return nil
}
https://play.golang.org/p/k_UlghLxZI
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论