我试图在每个属性中返回一个带有列表的json,但我总是将列表作为空列表获取。似乎我在结构中有一个错误,但我找不到它。
我有两个结构:
type CalendarDay struct {
day int `json:"day"`
weekday string `json:"weekday"`
}
type CalendarYear struct {
January []CalendarDay `json:"january"`
February []CalendarDay `json:"february"`
March []CalendarDay `json:"march"`
April []CalendarDay `json:"april"`
May []CalendarDay `json:"may"`
June []CalendarDay `json:"june"`
July []CalendarDay `json:"july"`
August []CalendarDay `json:"august"`
September []CalendarDay `json:"september"`
October []CalendarDay `json:"october"`
November []CalendarDay `json:"november"`
December []CalendarDay `json:"december"`
}
我正在尝试将json作为:
返回{
"january": [{1 Thursday}, ...]
...
}
但我认为:
{
"january": [{}, {}, {} ...]
...
}
我的API是:
func Calendar(w http.ResponseWriter, r *http.Request) {
fmt.Println("GET /")
year := getYear(2015)
json.NewEncoder(w).Encode(year)
}
func getMonthDays(month time.Month, year int) []CalendarDay {
cdays := []CalendarDay{}
for i := 1; i <= daysIn(month, year); i++ {
date := time.Date(year, month, i, 0, 0, 0, 0, time.UTC)
weekday := date.Weekday()
cday := CalendarDay{
day: date.Day(),
weekday: weekday.String()}
cdays = append(cdays, cday)
}
return cdays
}
func getYear(year int) CalendarYear {
yearCal := CalendarYear{
January: getMonthDays(time.January, year),
February: getMonthDays(time.February, year),
March: getMonthDays(time.March, year),
April: getMonthDays(time.April, year),
May: getMonthDays(time.May, year),
June: getMonthDays(time.June, year),
July: getMonthDays(time.July, year),
August: getMonthDays(time.August, year),
September: getMonthDays(time.September, year),
October: getMonthDays(time.October, year),
November: getMonthDays(time.November, year),
December: getMonthDays(time.December, year)}
return yearCal
}
我做错了什么?
答案 0 :(得分:2)
Export CalendarDay中的字段,以大写字符开头。
type CalendarDay struct {
Day int `json:"day"`
Weekday string `json:"weekday"`
}
encoding / json包和类似的包忽略未导出的字段。