Home > Backend Development > Golang > How to Deserialize Non-RFC 3339 Time Formats in Go with `encoding/json`?

How to Deserialize Non-RFC 3339 Time Formats in Go with `encoding/json`?

Patricia Arquette
Release: 2024-12-18 20:57:10
Original
702 people have browsed it

How to Deserialize Non-RFC 3339 Time Formats in Go with `encoding/json`?

Deserializing Non-RFC 3339 Time Formats in Go with encoding/json

When using the encoding/json package in Go, the default behavior for unmarshaling time values is to strictly adhere to the RFC 3339 format. However, what if you encounter time formats that deviate from this standard?

Custom Time Type Implementation

To handle such situations, you can implement the json.Marshaler and json.Unmarshaler interfaces on a custom type. This allows you to define custom encoding and decoding logic for your specific time format.

Here's an example of a custom CustomTime type:

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

Usage in a Struct

To use the CustomTime type, you can embed it as a field in a struct:

type Args struct {
    Time CustomTime
}
Copy after login

Example

Here's an example of how to use the Args struct and CustomTime type to unmarshal a JSON string containing a non-RFC 3339 time format:

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

Output:

<nil>
2014-08-01 11:27:18 +0000 UTC
Copy after login

By implementing the custom CustomTime type, you can handle the deserialization of time formats that are not in RFC 3339 format.

The above is the detailed content of How to Deserialize Non-RFC 3339 Time Formats in Go with `encoding/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