Home > Backend Development > Golang > How to Decode Non-Standard Time Formats from JSON?

How to Decode Non-Standard Time Formats from JSON?

Mary-Kate Olsen
Release: 2024-11-08 20:41:02
Original
1020 people have browsed it

How to Decode Non-Standard Time Formats from JSON?

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"
}
Copy after login

Suppose we want to decode this into a Person struct:

type Person struct {
    Name string `json:"name"`
    BirthDate time.Time `json:"birth_date"`
}
Copy after login

Using the standard JSON decoder:

person := Person{}

decoder := json.NewDecoder(req.Body);

if err := decoder.Decode(&person); err != nil {
    log.Println(err)
}
Copy after login

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"`
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template