英文:
Why does go UnmarshalJSON receives Json Object and not just value
问题
我得到了以下自定义类型:
type TimeWithoutZone struct {
time.Time
}
编组工作正常:
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
}
但是在这里,日期无法解析:
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
}
它记录了:Parsing: {"time":"2016-09-06T11:06:16"}
,但我希望它只解析time
的值。
我做错了什么?这是相关的测试:
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)
}
}
我找到的所有示例,甚至Go时间包的默认解析器似乎都是这样工作的...
英文:
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
得分: 1
哇,我在这一行中写错了类型:
parsed := TimeWithoutZone{}
应该是
parsed := TimeTestObj{}
...
英文:
Wow I just have the wrong type in this line:
parsed := TimeWithoutZone{}
must be
parsed := TimeTestObj{}
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论