如何从JSON解析非标准时间格式 [英] How to parse non standard time format from json
本文介绍了如何从JSON解析非标准时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我说我有以下json
lets say i have the following json
{
name: "John",
birth_date: "1996-10-07"
}
我想将其解码为以下结构
and i want to decode it into the following structure
type Person struct {
Name string `json:"name"`
BirthDate time.Time `json:"birth_date"`
}
像这样
person := Person{}
decoder := json.NewDecoder(req.Body);
if err := decoder.Decode(&person); err != nil {
log.Println(err)
}
这给我错误parsing time ""1996-10-07"" as ""2006-01-02T15:04:05Z07:00"": cannot parse """ as "T"
如果我要手动解析它,我会这样做
if i were to parse it manually i would do it like this
t, err := time.Parse("2006-01-02", "1996-10-07")
但是当时间值来自json字符串时我如何使解码器以上述格式解析它?
but when the time value is from a json string how do i get the decoder to parse it in the above format?
推荐答案
在这种情况下,您需要实现自定义的编组和解编功能.
That's a case when you need to implement custom marshal und unmarshal functions.
UnmarshalJSON(b []byte) error { ... }
MarshalJSON() ([]byte, error) { ... }
通过遵循 json包的Golang文档中的示例,您将获得像这样:
By following the example in the Golang documentation of json package you get something like:
// first create a type alias
type JsonBirthDate time.Time
// Add that to your struct
type Person struct {
Name string `json:"name"`
BirthDate JsonBirthDate `json:"birth_date"`
}
// imeplement Marshaler und Unmarshalere interface
func (j *JsonBirthDate) UnmarshalJSON(b []byte) error {
s := strings.Trim(string(b), "\"")
t, err := time.Parse("2006-01-02", s)
if err != nil {
return err
}
*j = JsonBirthDate(t)
return nil
}
func (j JsonBirthDate) MarshalJSON() ([]byte, error) {
return json.Marshal(j)
}
// Maybe a Format function for printing your date
func (j JsonBirthDate) Format(s string) string {
t := time.Time(j)
return t.Format(s)
}
这篇关于如何从JSON解析非标准时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文