覆盖由json.Marshal使用的布局来格式化time.Time [英] Override the layout used by json.Marshal to format time.Time

查看:225
本文介绍了覆盖由json.Marshal使用的布局来格式化time.Time的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Golang中,是否有一种方法可以在编制时间时使通用编码/ json Marshal使用不同的布局。


$ b基本上我有这个结构:

  s:= {starttime:time.Now(),name:ali} 

我想用 encdoding / json Marshal 函数编码为json,但我想用我的自定义布局,我想象的地方 time.Format(layout)被调用,我想控制这个布局,

解决方案

正如zeebo的回答所激发的,并且在评论中对这个答案进行了概括: http://play.golang.org/p/pUCBUgrjZC

  package main 

importfmt
importtime
importencoding / json

type jsonTime struct {
time.Time
f string
}

func(j jsonTime)format()string {
return j.Time.Format(jf)
}

func(j jsonTime)MarshalText()([] byte ,错误){
return [] byte(j.format()),nil
}

func(j jsonTime)MarshalJSON()([] byte,error){
return [] byte(```+ j.format()+``),nil
}

func main(){
jt:= jsonTime {time.Now(),time.Kitchen}
如果jt.Before(time.Now().AddDate(0,0,1)){// 1
x:= map [string]接口{} {
foo:jt,
bar:baz,
}
data,err:= json.Marshal(x)
if err!= nil {
panic(err)
}
fmt.Printf(%s,data)
}
}

此解决方案将时间嵌入到jsonTime结构中。嵌入式将所有time.Time的方法提升为jsonTime结构体,允许它们在没有显式类型转换的情况下使用(参见// 1)。

嵌入time.Time具有下行也推广MarshalJSON方法,其中编码/ json封送代码的优先级高于MarshalText方法,以实现向后兼容性原因(,MarshalJSON早于此)。因此,使用了默认的time.Time格式,而不是MarshalText提供的自定义格式。



为了克服这个问题,我们重写了jsonTime结构的MarshalJSON。 >

In Golang, is there a way to make the generic encoding/json Marshal to use a different layout when Marshaling the time.Time fields?

Basically I have this struct:

s := {"starttime":time.Now(), "name":"ali"}

and I want to encoding to json using encdoding/json's Marshal function, but I want to use my custom layout, I imagine somewhere time.Format(layout) is being called, I want to control that layout,

解决方案

As inspired by zeebo's answer and hashed out in the comments to that answer:

http://play.golang.org/p/pUCBUgrjZC

package main

import "fmt"
import "time"
import "encoding/json"

type jsonTime struct {
    time.Time
    f string
}

func (j jsonTime) format() string {
    return j.Time.Format(j.f)
}

func (j jsonTime) MarshalText() ([]byte, error) {
    return []byte(j.format()), nil
}

func (j jsonTime) MarshalJSON() ([]byte, error) {
    return []byte(`"` + j.format() + `"`), nil
}

func main() {
    jt := jsonTime{time.Now(), time.Kitchen}
    if jt.Before(time.Now().AddDate(0, 0, 1)) { // 1
        x := map[string]interface{}{
            "foo": jt,
            "bar": "baz",
        }
        data, err := json.Marshal(x)
        if err != nil {
            panic(err)
        }
        fmt.Printf("%s", data)
    }
}

This solution embeds the time.Time into the jsonTime struct. Embedding promotes all of time.Time's methods to the jsonTime struct, allowing their use without explicit type conversion (see // 1).

Embedding a time.Time has the downside of also promoting the MarshalJSON method, which the encoding/json marshaling code prioritizes higher than the MarshalText method for backwards compatibility reasons (MarshalText was added in Go 1.2, MarshalJSON predates that). As a result the default time.Time format is used instead of a custom format provided by MarshalText.

To overcome this problem we override MarshalJSON for the jsonTime struct.

这篇关于覆盖由json.Marshal使用的布局来格式化time.Time的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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