Customizing JSON Time Unmarshaling in Go
When dealing with JSON data that contains time values, the encoding/json package in Go can be limiting if the time format doesn't adhere to RFC 3339. While it's possible to manually transform the time into RFC 3339 format for parsing, there's a more efficient approach.
Implement Marshaler/Unmarshaler Interfaces
To handle custom time formats, create a custom type that implements the json.Marshaler and json.Unmarshaler interfaces. This allows you to define how the time value should be serialized and deserialized.
Here's an example custom type called CustomTime:
type CustomTime struct { time.Time } const ctLayout = "2006/01/02|15:04:05" func (ct *CustomTime) UnmarshalJSON(b []byte) (err error) { s := strings.Trim(string(b), "\"") if s == "null" { ct.Time = time.Time{} return } ct.Time, err = time.Parse(ctLayout, s) return } func (ct *CustomTime) MarshalJSON() ([]byte, error) { if ct.Time.IsZero() { return []byte("null"), nil } return []byte(fmt.Sprintf("\"%s\"", ct.Time.Format(ctLayout))), nil } var nilTime = (time.Time{}).UnixNano() func (ct *CustomTime) IsSet() bool { return !ct.IsZero() }
In this custom type:
Usage
Once the CustomTime type is defined, it can be used as a struct field to deserialize JSON data with custom time formats.
type Args struct { Time CustomTime } var data = ` { "Time": "2014/08/01|11:27:18" } ` func main() { a := Args{} fmt.Println(json.Unmarshal([]byte(data), &a)) fmt.Println(a.Time.String()) }
This example successfully deserializes the JSON data where the Time field is in a custom "2006/01/02|15:04:05" format.
The above is the detailed content of How Can I Customize JSON Time Unmarshaling in Go to Handle Non-RFC 3339 Formats?. For more information, please follow other related articles on the PHP Chinese website!