为什么go的UnmarshalJSON方法接收JSON对象而不仅仅是值?

huangapple go评论68阅读模式
英文:

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{}

...

huangapple
  • 本文由 发表于 2016年9月6日 17:51:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/39345921.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定