在Go中处理不同时间格式的反序列化的合适方式是什么?在仅接受的RFC3339中,编码/json包似乎是完全僵化的。我可以反序列化为字符串,将其转换为RFC3339,然后对其进行解组,但我并不真的想这样做。有更好的解决方案吗?
发布于 2014-08-02 04:37:43
您必须在自定义类型上实现json.Marshaler / json.Unmarshaler接口,并改用example
type CustomTime struct {
time.Time
}
const ctLayout = "2006/01/02|15:04:05"
func (ct *CustomTime) UnmarshalJSON(b []byte) (err error) {
s := strings.Trim(string(b), "\"")
if s == "null" {
ct.Time = time.Time{}
return
}
ct.Time, err = time.Parse(ctLayout, s)
return
}
func (ct *CustomTime) MarshalJSON() ([]byte, error) {
if ct.Time.UnixNano() == nilTime {
return []byte("null"), nil
}
return []byte(fmt.Sprintf("\"%s\"", ct.Time.Format(ctLayout))), nil
}
var nilTime = (time.Time{}).UnixNano()
func (ct *CustomTime) IsSet() bool {
return ct.UnixNano() != nilTime
}
type Args struct {
Time CustomTime
}
var data = `
{"Time": "2014/08/01|11:27:18"}
`
func main() {
a := Args{}
fmt.Println(json.Unmarshal([]byte(data), &a))
fmt.Println(a.Time.String())
}编辑:添加CustomTime.IsSet()以检查其是否实际设置,以供将来参考。
发布于 2014-08-02 04:20:48
编码/解码是由time.Time本身在MarshalJSON和UnamrshalJSON方法中完成的。您可以创建自己的time.Time类型,并覆盖这些函数以随心所欲地使用json。
type Time struct {
time.Time
}
// returns time.Now() no matter what!
func (t *Time) UnmarshalJSON(b []byte) error {
// you can now parse b as thoroughly as you want
*t = Time{time.Now()}
return nil
}
type Config struct {
T Time
}
func main() {
c := Config{}
json.Unmarshal([]byte(`{"T": "bad-time"}`), &c)
fmt.Printf("%+v\n", c)
}https://stackoverflow.com/questions/25087960
复制相似问题