0 day streak
go / intermediate
Snippet

Implementing Custom JSON Serialization for Date Fields

By default, Go's json.Marshal formats types using default serialization rules. By implementing the json.Marshaler interface (defining a MarshalJSON() ([]byte, error) method), you can customize exactly how a type is rendered in JSON format, which is useful for custom date formatting, masking sensitive fields, or changing structures.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main
import (
"encoding/json"
"fmt"
"time"
)
type CustomDate time.Time
func (cd CustomDate) MarshalJSON() ([]byte, error) {
formatted := fmt.Sprintf("\"%s\"", time.Time(cd).Format("2006-01-02"))
return []byte(formatted), nil
}
type Event struct {
Name string `json:"name"`
Date CustomDate `json:"date"`
}
func main() {
evt := Event{
Name: "Gala Concert",
Date: CustomDate(time.Date(2026, 7, 5, 0, 0, 0, 0, time.UTC)),
}
data, _ := json.Marshal(evt)
fmt.Println(string(data))
}
Breakdown
1
type CustomDate time.Time
Creates a custom type alias based on time.Time to avoid changing the global behavior of time.Time.
2
func (cd CustomDate) MarshalJSON() ([]byte, error) {
Implements the json.Marshaler interface to override default serialization for CustomDate.
3
formatted := fmt.Sprintf("\"%s\"", time.Time(cd).Format("2006-01-02"))
Formats the time as a YYYY-MM-DD string enclosed in JSON double quotes.
4
data, _ := json.Marshal(evt)
Serializes the Event struct, automatically calling MarshalJSON for the Date field.