Iorrrrrrrrrr
Iorrrrrrrrrr

Reputation: 422

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

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.

Upvotes: 0

Views: 4630

Answers (1)

mkopriva
mkopriva

Reputation: 38233

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

Upvotes: 2

Related Questions