Custom Un/Marshaling for Non-Standard JSON Time Formats
When dealing with JSON data that contains time values in non-standard formats, the built-in JSON decoder may encounter errors. To handle such situations, custom marshal and unmarshal functions can be implemented.
Consider the following JSON:
{ "name": "John", "birth_date": "1996-10-07" }
And the desired Go struct:
type Person struct { Name string `json:"name"` BirthDate time.Time `json:"birth_date"` }
Using the standard JSON decoder would result in an error while parsing the "birth_date" field. To customize this behavior, a type alias can be created and added to the struct:
type JsonBirthDate time.Time
Then, custom marshal and unmarshal functions are implemented:
func (j *JsonBirthDate) UnmarshalJSON(b []byte) error { s := strings.Trim(string(b), `"`) // Remove quotes t, err := time.Parse("2006-01-02", s) if err != nil { return err } *j = JsonBirthDate(t) return nil } func (j JsonBirthDate) MarshalJSON() ([]byte, error) { return json.Marshal(time.Time(j)) }
With these custom functions, the JSON can now be decoded into the Go struct as intended:
person := Person{} decoder := json.NewDecoder(req.Body); if err := decoder.Decode(&person); err != nil { log.Println(err) } // Print the birth date using the Format function fmt.Println(person.BirthDate.Format("2006-01-02"))
The above is the detailed content of How to Custom Unmarshal Non-Standard JSON Time Formats in Go?. For more information, please follow other related articles on the PHP Chinese website!