Home > Backend Development > Golang > How Can I Customize JSON Time Unmarshaling in Go to Handle Non-RFC 3339 Formats?

How Can I Customize JSON Time Unmarshaling in Go to Handle Non-RFC 3339 Formats?

Linda Hamilton
Release: 2024-12-18 21:09:13
Original
989 people have browsed it

How Can I Customize JSON Time Unmarshaling in Go to Handle Non-RFC 3339 Formats?

Customizing JSON Time Unmarshaling in Go

When dealing with JSON data that contains time values, the encoding/json package in Go can be limiting if the time format doesn't adhere to RFC 3339. While it's possible to manually transform the time into RFC 3339 format for parsing, there's a more efficient approach.

Implement Marshaler/Unmarshaler Interfaces

To handle custom time formats, create a custom type that implements the json.Marshaler and json.Unmarshaler interfaces. This allows you to define how the time value should be serialized and deserialized.

Here's an example custom type called CustomTime:

type CustomTime struct {
    time.Time
}

const ctLayout = "2006/01/02|15:04:05"

func (ct *CustomTime) UnmarshalJSON(b []byte) (err error) {
    s := strings.Trim(string(b), "\"")
    if s == "null" {
        ct.Time = time.Time{}
        return
    }
    ct.Time, err = time.Parse(ctLayout, s)
    return
}

func (ct *CustomTime) MarshalJSON() ([]byte, error) {
    if ct.Time.IsZero() {
        return []byte("null"), nil
    }
    return []byte(fmt.Sprintf("\"%s\"", ct.Time.Format(ctLayout))), nil
}

var nilTime = (time.Time{}).UnixNano()
func (ct *CustomTime) IsSet() bool {
    return !ct.IsZero()
}
Copy after login

In this custom type:

  • UnmarshalJSON converts the JSON string into a time.Time value using a specified custom layout.
  • MarshalJSON converts the time.Time value into a JSON string using the same custom layout.
  • IsSet is an optional method to check if a CustomTime value has been set (not zero).

Usage

Once the CustomTime type is defined, it can be used as a struct field to deserialize JSON data with custom time formats.

type Args struct {
    Time CustomTime
}

var data = `
    {
        "Time": "2014/08/01|11:27:18"
    }
`

func main() {
    a := Args{}
    fmt.Println(json.Unmarshal([]byte(data), &a))
    fmt.Println(a.Time.String())
}
Copy after login

This example successfully deserializes the JSON data where the Time field is in a custom "2006/01/02|15:04:05" format.

The above is the detailed content of How Can I Customize JSON Time Unmarshaling in Go to Handle Non-RFC 3339 Formats?. 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