我最近一直在玩围棋,它很棒。我似乎无法弄清楚的事情(在查看文档和博客文章之后)是如何让 time.Time
类型在 编码时格式化为我想要的任何格式>json.NewEncoder.Encode
这是一个最小的代码示例:
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
}
}
理想情况下,我想发送一个请求并将 Stamp 字段返回为 May 15, 2014
而不是 2014-05-16T08:28:06.801064-04: 00
但我不太确定如何,我知道我可以将 json:stamp
添加到文档类型声明中,以使用名称戳记而不是 Stamp 对字段进行编码,但我不知道不知道这些类型的东西被称为什么,所以我什至不确定用谷歌搜索是否也有某种类型的格式化选项。
有没有人有关于这些类型标记(或任何它们被称为)主题的示例或良好文档页面的链接,或者关于我如何告诉 JSON 编码器处理 time.Time
字段?
仅供引用,我查看了以下页面:here和 here当然,at the official docs
最佳答案
你可以做的是,将 time.Time 包装为你自己的自定义类型,并使其实现 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
}
让你的初始化看起来像:
testDoc := model.Document{"Meeting Notes", "These are some notes", JSONTime(time.Now()), "Bacon"}
就是这样。如果你想解码,还有 Unmarshaler
接口(interface)。
https://stackoverflow.com/questions/23695479/