Home >Backend Development >Golang >How to Deserialize Non-RFC 3339 Time Formats in Go with `encoding/json`?
When using the encoding/json package in Go, the default behavior for unmarshaling time values is to strictly adhere to the RFC 3339 format. However, what if you encounter time formats that deviate from this standard?
To handle such situations, you can implement the json.Marshaler and json.Unmarshaler interfaces on a custom type. This allows you to define custom encoding and decoding logic for your specific time format.
Here's an example of a custom CustomTime type:
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() }
To use the CustomTime type, you can embed it as a field in a struct:
type Args struct { Time CustomTime }
Here's an example of how to use the Args struct and CustomTime type to unmarshal a JSON string containing a non-RFC 3339 time format:
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()) }
Output:
<nil> 2014-08-01 11:27:18 +0000 UTC
By implementing the custom CustomTime type, you can handle the deserialization of time formats that are not in RFC 3339 format.
The above is the detailed content of How to Deserialize Non-RFC 3339 Time Formats in Go with `encoding/json`?. For more information, please follow other related articles on the PHP Chinese website!