dsh1956 2014-12-17 03:15
浏览 143

Golang JSON Marshal / Unmarshal postgres now()

I'm using postgres' now() as a default for my created timestamp, which is generates this:

 id | user_id | title | slug | content |          created           
----+---------+-------+------+---------+----------------------------
  1 |       1 | Foo   | foo  | bar     | 2014-12-16 19:41:31.428883
  2 |       1 | Bar   | bar  | whiz    | 2014-12-17 02:03:31.566419

I tried to use json.Marshal and json.Unmarshal and ended up getting this error:

parsing time ""2014-12-16 19:41:31.428883"" as ""2006-01-02T15:04:05Z07:00"": cannot parse " 19:41:31.428883"" as "T"

So I decided to try and create a custom time, but can't seem to get anything working.

Post.go

package models

type Post struct {
    Id      int    `json:"id"`
    UserId  int    `json:"user_id"`
    Title   string `json:"title"`
    Slug    string `json:"slug"`
    Content string `json:"content"`
    Created Tick   `json:"created"`
    User    User   `json:"user"`
}

Tick.go

package models

import (
    "fmt"
    "time"
)

type Tick struct {
    time.Time
}

var format = "2006-01-02T15:04:05.999999-07:00"

func (t *Tick) MarshalJSON() ([]byte, error) {
    return []byte(t.Time.Format(format)), nil
}

func (t *Tick) UnmarshalJSON(b []byte) (err error) {
    b = b[1 : len(b)-1]
    t.Time, err = time.Parse(format, string(b))
    return
}

Any help would be much appreciated, running what I've wrote here gives me this:

json: error calling MarshalJSON for type models.Tick: invalid character '0' after top-level value

  • 写回答

2条回答 默认 最新

  • duan19911992 2014-12-17 14:39
    关注

    it's seems like you're using the wrong format. Postgres uses RFC 3339, which is already defined in the time package. This should work:

    time.Parse(time.RFC3339, string(b))
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用