Formatting Timestamps in Outgoing JSON with Custom Types
To format timestamps during JSON encoding, you can create a custom type that implements the Marshaler interface. By doing so, you gain control over the serialization process, allowing you to specify the desired format.
Implementing the Marshaler Interface
The Marshaler interface requires a single method, MarshalJSON, which returns a byte slice representing the JSON-encoded data and an error if any. In this case, you'll define a custom type that wraps time.Time and implements MarshalJSON.
Here's an example implementation:
type JSONTime time.Time func (t JSONTime)MarshalJSON() ([]byte, error) { // Format the timestamp in the desired format stamp := fmt.Sprintf("\"%s\"", time.Time(t).Format("Mon Jan _2")) return []byte(stamp), nil }
Updating the Document Struct
In your Document struct, replace time.Time with the custom JSONTime type for the Stamp field:
type Document struct { Name string Content string Stamp JSONTime Author string }
Initializing the Document
When initializing the Document instance, use JSONTime(time.Now()) instead of time.Now():
testDoc := model.Document{"Meeting Notes", "These are some notes", JSONTime(time.Now()), "Bacon"}
By following these steps, you can format timestamps in your JSON responses according to your requirements. You can extend this concept to other custom types or scenarios as needed.
The above is the detailed content of How Can I Customize Timestamp Formatting in Go's JSON Output?. For more information, please follow other related articles on the PHP Chinese website!