Home >Backend Development >Golang >How to Handle Non-RFC 3339 Time Formats in Go's JSON Unmarshaling?
JSON Unmarshaling of Non-RFC 3339 Time Formats in Go
The default behavior of the encoding/json package in Go is to marshal and unmarshal time values in RFC 3339 format. However, what if you encounter JSON data with time values in a different format?
Solution with Manual Transformation
One approach is to deserialize the time value into a string, manually transform it into RFC 3339 format, and then apply json.Unmarshal again. While this method works, it introduces additional processing overhead and clutters code.
Custom Time Type
A more elegant solution is to implement the json.Marshaler and json.Unmarshaler interfaces on a custom time type. This allows for custom handling of time value serialization and deserialization.
Example Implementation
Here's an example of a custom time type named 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 time type:
Usage
Now, you can use the CustomTime type in your JSON deserialization code:
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 approach allows you to handle non-RFC 3339 time formats in JSON data elegantly and efficiently without compromising flexibility. It also showcases the power of implementing custom json.Marshaler and json.Unmarshaler interfaces for handling data type serialization and deserialization.
The above is the detailed content of How to Handle Non-RFC 3339 Time Formats in Go's JSON Unmarshaling?. For more information, please follow other related articles on the PHP Chinese website!