Home  >  Article  >  Backend Development  >  How to Handle Non-Standard Time Formats in JSON Parsing?

How to Handle Non-Standard Time Formats in JSON Parsing?

DDD
DDDOriginal
2024-11-09 05:03:02340browse

How to Handle Non-Standard Time Formats in JSON Parsing?

Parsing Non-Standard Time Formats in JSON

In typical JSON parsing scenarios, time values are expected to adhere to the RFC 3339 format ("2006-01-02T15:04:05Z07:00"). However, when dealing with non-standard time formats, the default JSON decoder encounters issues.

To overcome this, one can implement custom marshal and unmarshal methods for a custom data type that represents the non-standard time format. For instance:

// Create a type alias for the non-standard time format
type JsonBirthDate time.Time

// Implement UnmarshalJSON to handle conversion from JSON string to time.Time
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 to handle conversion from time.Time to JSON string
func (j JsonBirthDate) MarshalJSON() ([]byte, error) {
    return json.Marshal(time.Time(j))
}

Now, incorporate this custom type into the Person struct:

type Person struct {
    Name string `json:"name"`
    BirthDate JsonBirthDate `json:"birth_date"`
}

By utilizing these custom methods, the JSON decoder can now successfully parse the non-standard time format:

person := Person{}
decoder := json.NewDecoder(req.Body)
if err := decoder.Decode(&person); err != nil {
    log.Println(err)
}

The above is the detailed content of How to Handle Non-Standard Time Formats in JSON Parsing?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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