How to Custom Unmarshal Non-Standard JSON Time Formats in Go?

DDD
Release: 2024-11-16 14:48:02
Original
393 people have browsed it

How to Custom Unmarshal Non-Standard JSON Time Formats in Go?

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

And the desired Go struct:

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

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

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template