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

How to Handle Non-RFC 3339 Time Formats When Unmarshaling JSON in Go?

DDD
DDDOriginal
2024-12-30 22:02:11533browse

How to Handle Non-RFC 3339 Time Formats When Unmarshaling JSON in Go?

Custom JSON Unmarshaling for Non-RFC 3339 Time Formats

The encoding/json package in Go strictly adheres to the RFC 3339 time format when deserializing JSON data. This can be inconvenient when dealing with time formats that deviate from this standard.

Solution: Implementing Custom Marshalers and Unmarshalers

Instead of modifying the existing JSON data or relying on intermediate conversion steps, a more suitable solution is to implement the json.Marshaler and json.Unmarshaler interfaces on a custom type.

The following example demonstrates how to create a custom type (CustomTime) that handles deserialization of a specific non-RFC 3339 time format:

import (
    "fmt"
    "strconv"
    "strings"
    "time"

    "github.com/golang/protobuf/ptypes/timestamp"
)

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()
}

type Args struct {
    Time CustomTime
}

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

func main() {
    a := Args{}
    if err := json.Unmarshal([]byte(data), &a); err != nil {
        fmt.Println("Error unmarshaling: ", err)
        return
    }

    if !a.Time.IsSet() {
        fmt.Println("Time not set")
    } else {
        fmt.Println(a.Time.String())
    }
}

Note: The CustomTime.IsSet() method checks if the Time field is not zero, providing a way to determine if the time value was actually set or not.

By implementing custom Marshalers and Unmarshalers, you gain the flexibility to handle time formats that may deviate from the RFC 3339 standard, allowing for seamless JSON data deserialization in Go.

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