dongra1984 2016-09-06 09:51
浏览 60

为什么去UnmarshalJSON会收到Json Object而不仅仅是值

I got the following custom type:

type TimeWithoutZone struct {
    time.Time
}

The Marshaling works fine:

const timeWithoutZoneFormat = "2006-01-02T15:04:05"
func (t *TimeWithoutZone) MarshalJSON() ([]byte, error) {
    stamp := fmt.Sprintf(`"%s"`, t.Time.Format(timeWithoutZoneFormat ))
    return []byte(stamp), nil
}

But here the date can not be parsed:

func (t *TimeWithoutZone) UnmarshalJSON(data []byte) (err error) {
    log.Println("Parsing: " + string(data))
    t.Time, err = time.Parse(`"` + timeWithoutZoneFormat + `"`, string(data))

    if err != nil {
        return err
    }
    return nil
}

It logs: Parsing: {"time":"2016-09-06T11:06:16"} but I would expect it to parse just the value of time

What am I doing wrong? here is the related test:

type TimeTestObj struct {
    Time TimeWithoutZone `json:"time"`
}

func TestParseDataWithoutTimezone(t *testing.T) {
    parsed := TimeWithoutZone{}

    data := `{"time":"2016-09-06T11:06:16"}`
    err := json.Unmarshal([]byte(data), &parsed)

    if err != nil {
        t.Error(err)
    }

    if parsed.Unix() != 1473152776 {
        t.Error(parsed.Unix(), "!=", 1473152776)
    }
}

All the examples I find, and even the default parser from the Go time package seem to work that way...

  • 写回答

1条回答 默认 最新

  • douhensheng1131 2016-09-06 09:53
    关注

    Wow I just have the wrong type in this line:

    parsed := TimeWithoutZone{}
    

    must be

    parsed := TimeTestObj{}
    

    ...

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据