在Golang中输出JSON格式的时间戳? [英] Format Timestamp in outgoing JSON in Golang?

查看:167
本文介绍了在Golang中输出JSON格式的时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近和Go一起玩,真棒。我似乎无法弄清楚的事情(查看文档和博客文章之后)是如何获取 time.Time 类型来格式化为任何我想要的格式当它被编码时> json.NewEncoder.Encode



这是一个最简单的代码示例:

 包主

类型文档结构{
名称字符串
内容字符串
印记时间。时间
作者字符串
}

func sendResponse(数据接口{},w http.ResponseWriter,r * http.Request){
_,err:= json .marshal(data)
j:= json.NewEncoder(w)
if err == nil {
encodedErr:= j.Encode(data)$ b $如果encodedErr!= nil { (b
$ code

$ else b $ b $ code


$ b func main() {
http.HandleFunc(/ document,control.HandleDocuments)
http.ListenAndServe(localhost:4000,nil)


func HandleDocuments(w http.ResponseWriter,r * http.Request){
w.Header()。Set(Content-Type,application / json)
w.Header()。Set(Access-Control-Allow-Origin,*)

switch r.Method {
caseGET:
//逻辑剪辑
testDoc:= model.Document {Meeting Notes,These are some notes,time.Now(),Bacon}
sendResponse(testDoc,w,r )

casePOST:
casePUT:
caseDELETE:
默认值:
//剪切
}
}

理想情况下,我想发送一个请求并获取Stamp字段如 2014年5月15日而不是 2014-05-16T08:28:06.801064-04:



但是我不确定如何,我知道可以在Document类型声明中添加 json:stamp 使用名字戳而不是邮票来编码字段,但我不知道这些类型的东西被称为什么,所以我甚至不知道如何谷歌找到是否有某种类型的格式化选项。

有没有人有链接到一个例子或良好的文档页面的主题这些类型的标记(或无论他们被称为)或如何我可以告诉JSON编码器处理 time.Time 字段?

仅供参考,我已经看过这些页面:这里这里,当然,在官方文档

解决方案

可以做的就是把time.Time作为自己的自定义类型,并使其实现 Marshaler 接口:

 MarshalJSON()([] byte,error)

code $ <$ $ $ $ $ $>

所以你要做的就是这样:

 类型JSONTime time.Time 

func(t JSONTime)MarshalJSON()([] byte,error){
//在这里进行序列化
stamp:= fmt.Sprintf(\ (Times New Year))
return [] byte(stamp),nil
}

并创建文档:

 类型Document结构{
名称字符串
内容字符串
戳记JSONTime
作者字符串
}

并且你的初始化看起来像:

 testDoc:= model.Document {Meeting Notes,These are some notes,JSONTime(time.Now()),Bacon} 

就是这样。如果你想解组,也有 Unmarshaler 接口。


I've been playing with Go recently and it's awesome. The thing I can't seem to figure out (after looking through documentation and blog posts) is how to get the time.Time type to format into whatever format I'd like when it's encoded by json.NewEncoder.Encode

Here's a minimal Code example:

package main

type Document struct {
    Name        string
    Content     string
    Stamp       time.Time
    Author      string
}

func sendResponse(data interface{}, w http.ResponseWriter, r * http.Request){
     _, err := json.Marshal(data)
    j := json.NewEncoder(w)
    if err == nil {
        encodedErr := j.Encode(data)
        if encodedErr != nil{
            //code snipped
        }
    }else{
       //code snipped
    }
}

func main() {
    http.HandleFunc("/document", control.HandleDocuments)
    http.ListenAndServe("localhost:4000", nil)
}

func HandleDocuments(w http.ResponseWriter,r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.Header().Set("Access-Control-Allow-Origin", "*")

    switch r.Method {
        case "GET": 
            //logic snipped
            testDoc := model.Document{"Meeting Notes", "These are some notes", time.Now(), "Bacon"}    
            sendResponse(testDoc, w,r)
            }
        case "POST":
        case "PUT":
        case "DELETE":
        default:
            //snipped
    }
}

Ideally, I'd like to send a request and get the Stamp field back as something like May 15, 2014 and not 2014-05-16T08:28:06.801064-04:00

But I'm not really sure how, I know I can add json:stamp to the Document type declaration to get the field to be encoded with the name stamp instead of Stamp, but I don't know what those types of things are called, so I'm not even sure what to google for to find out if there is some type of formatting option in that as well.

Does anyone have a link to the an example or good documentation page on the subject of those type mark ups (or whatever they're called) or on how I can tell the JSON encoder to handle time.Time fields?

Just for reference, I have looked at these pages: here and here and of course, at the official docs

解决方案

What you can do is, wrap time.Time as your own custom type, and make it implement the Marshaler interface:

type Marshaler interface {
    MarshalJSON() ([]byte, error)
}

So what you'd do is something like:

type JSONTime time.Time

func (t JSONTime)MarshalJSON() ([]byte, error) {
    //do your serializing here
    stamp := fmt.Sprintf("\"%s\"", time.Time(t).Format("Mon Jan _2"))
    return []byte(stamp), nil
}

and make document:

type Document struct {
    Name        string
    Content     string
    Stamp       JSONTime
    Author      string
}

and have your intialization look like:

 testDoc := model.Document{"Meeting Notes", "These are some notes", JSONTime(time.Now()), "Bacon"}    

And that's about it. If you want unmarshaling, there is the Unmarshaler interface too.

这篇关于在Golang中输出JSON格式的时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆