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 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧