What is the appropriate way to handle deserialization of different time formats in Go? The encoding/json package seems to be entirely rigid in only accepted RFC 3339. I can deserialize into a string, transform that into RFC 3339 and then unmarshal it but I don't really want to do that. Any better solutions?
2条回答 默认 最新
- doufan9395 2014-08-01 20:37关注
You will have to implement the
json.Marshaler
/json.Unmarshaler
interfaces on a custom type and use that instead, an 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()) }
edit: added
CustomTime.IsSet()
to check it was actually set or not, for future reference.本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
- ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
- ¥20 有关区间dp的问题求解
- ¥15 多电路系统共用电源的串扰问题
- ¥15 slam rangenet++配置
- ¥15 有没有研究水声通信方面的帮我改俩matlab代码
- ¥15 ubuntu子系统密码忘记
- ¥15 保护模式-系统加载-段寄存器
- ¥15 电脑桌面设定一个区域禁止鼠标操作
- ¥15 求NPF226060磁芯的详细资料