我有一个名为MonthYear
的类型定义如下:
type MonthYear time.Time
func (my *MonthYear) MarshalJSON() ([]byte, error) {
t := time.Time(*my)
return json.Marshal(&struct {
Month int `json:"month"`
Year int `json:"year"`
}{
Month: int(t.Month()) - 1,
Year: t.Year(),
})
}
我包含了很多不同的结构体,比如:
type Event struct {
Name string `json:"name"`
Date MonthYear
}
type Item struct {
Category string `json:"category"`
Date MonthYear
}
我该如何将
MonthYear
类型内联,以便生成的JSON没有任何嵌入对象?我希望结果看起来像
{ "name": "party", "month": 2, "year": 2017 }
和{ "category": "art", "month": 3, "year": 2016 }
,而无需为每个结构编写MarshalJSON。