Home > Article > Backend Development > How to Customize the JSON Layout for time.Time Fields in Golang?
In Golang, the encoding/json.Marshal function is commonly used to convert objects to JSON. However, under default settings, it may not align with the desired JSON layout. This article illustrates a solution to override the default layout and customize the format used by time.Time fields during JSON marshalling.
Let's assume you have a struct s with a time.Time field named starttime. When marshalling this struct to JSON, you want to use a specific custom layout.
s := {"starttime":time.Now(), "name":"ali"}
To achieve this, we can create a custom type that embeds time.Time and overrides both MarshalText and MarshalJSON methods.
<code class="go">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 }</code>
By overriding MarshalText, we control how the jsonTime type converts its value to a text form, allowing us to specify the custom layout. Additionally, by overriding MarshalJSON, we ensure the overridden method is used instead of the built-in time.Time implementation for JSON marshalling.
With the custom jsonTime type, you can now marshal your s struct using the desired layout:
<code class="go">jt := jsonTime{time.Now(), time.Kitchen} x := map[string]interface{}{ "foo": jt, "bar": "baz", } data, err := json.Marshal(x) if err != nil { panic(err) }</code>
This will produce a JSON string with the starttime field formatted according to the time.Kitchen layout.
The above is the detailed content of How to Customize the JSON Layout for time.Time Fields in Golang?. For more information, please follow other related articles on the PHP Chinese website!