如何格式化传出JSON中的时间戳 [英] How to format timestamp in outgoing JSON

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

问题描述

我最近一直在玩Go,它很棒.在浏览文档和博客文章之后,我似乎无法弄清楚的是如何使time.Time类型格式化为json.NewEncoder.Encode

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
    }
}

理想情况下,我想发送一个请求并以类似May 15, 2014而不是2014-05-16T08:28:06.801064-04:00

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

但是我不太确定该怎么做,我知道可以在文档类型声明中添加json:stamp,以使用名称戳而不是戳来对字段进行编码,但是我不知道这些类型是什么事情被称为,所以我什至不知道该找些什么,以了解是否还有某种格式设置选项.

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.

有人在这些类型标记(或称为它们的名字)主题上或我如何告诉JSON编码器处理time.Time字段的示例或良好文档页面上是否有人链接?

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

推荐答案

您可以做的是,将time.Time包装为您自己的自定义类型,并使其实现Marshaler接口:

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)
}

所以您要做的是:

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
}

并制作文档:

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"}    

就是这样.如果要取消封送处理,也可以使用Unmarshaler界面.

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

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

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