Decoding Non-Standard Time Formats from JSON
When dealing with JSON data that contains non-standard time formats, standard JSON decoding may encounter issues as it expects specific time format patterns. To overcome this, custom marshal and unmarshal functions can be implemented.
For instance, consider the following JSON:
{ "name": "John", "birth_date": "1996-10-07" }
Suppose we want to decode this into a Person struct:
type Person struct { Name string `json:"name"` BirthDate time.Time `json:"birth_date"` }
Using the standard JSON decoder:
person := Person{} decoder := json.NewDecoder(req.Body); if err := decoder.Decode(&person); err != nil { log.Println(err) }
leads to an error, as the decoder cannot parse the non-standard time format. To address this, we can create a custom type alias for the time value and implement custom marshal and unmarshal functions.
An example implementation could be:
// Type alias type JsonBirthDate time.Time // Implement UnmarshalJSON func (j *JsonBirthDate) UnmarshalJSON(b []byte) error { s := strings.Trim(string(b), `"`) t, err := time.Parse("2006-01-02", s) if err != nil { return err } *j = JsonBirthDate(t) return nil } // Implement MarshalJSON func (j JsonBirthDate) MarshalJSON() ([]byte, error) { return json.Marshal(time.Time(j)) } // Example use in struct type Person struct { Name string `json:"name"` BirthDate JsonBirthDate `json:"birth_date"` }
With these custom functions, the JSON data can now be successfully decoded into the target Person struct, with the non-standard time format appropriately parsed.
The above is the detailed content of How to Decode Non-Standard Time Formats from JSON?. For more information, please follow other related articles on the PHP Chinese website!