douhao2011 2017-07-25 12:28
浏览 346
已采纳

如何从Golang中的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"`
}

like this

person := Person{}

decoder := json.NewDecoder(req.Body);

if err := decoder.Decode(&person); err != nil {
    log.Println(err)
}

which gives me the error 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")

but when the time value is from a json string how do i get the decoder to parse it in the above format?

  • 写回答

3条回答 默认 最新

  • dsy19811981 2017-07-25 12:59
    关注

    That's a case when you need to implement custom marshal und unmarshal functions.

    UnmarshalJSON(b []byte) error { ... }
    
    MarshalJSON() ([]byte, error) { ... }
    

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料