"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Custom Unmarshal Non-Standard JSON Time Formats in Go?

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

Published on 2024-12-23
Browse:281

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"
}

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"))
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3