Go语言 如何从json解析非标准时间格式

oknrviil  于 2023-03-21  发布在  Go
关注(0)|答案(4)|浏览(159)

假设我有下面的json

{
    name: "John",
    birth_date: "1996-10-07"
}

我想把它解码成下面的结构

type Person struct {
    Name string `json:"name"`
    BirthDate time.Time `json:"birth_date"`
}

像这样

person := Person{}

decoder := json.NewDecoder(req.Body);

if err := decoder.Decode(&person); err != nil {
    log.Println(err)
}

得到的误差是parsing time ""1996-10-07"" as ""2006-01-02T15:04:05Z07:00"": cannot parse """ as "T"
如果我手动解析它,我会这样做

t, err := time.Parse("2006-01-02", "1996-10-07")

但是当时间值来自JSON字符串时我如何让解码器以上面的格式解析它?

zi8p0yeb

zi8p0yeb1#

这就是需要实现自定义编组和解组函数的情况。

UnmarshalJSON(b []byte) error { ... }

MarshalJSON() ([]byte, error) { ... }

按照json包的Golang文档中的示例操作,您会得到如下内容:

// First create a type alias
type JsonBirthDate time.Time

// Add that to your struct
type Person struct {
    Name string `json:"name"`
    BirthDate JsonBirthDate `json:"birth_date"`
}

// Implement Marshaler and Unmarshaler interface
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
}
    
func (j JsonBirthDate) MarshalJSON() ([]byte, error) {
    return json.Marshal(time.Time(j))
}

// Maybe a Format function for printing your date
func (j JsonBirthDate) Format(s string) string {
    t := time.Time(j)
    return t.Format(s)
}
fkaflof6

fkaflof62#

如果有很多struct,而你只是实现自定义的marshal和unmarshal函数,那么你需要做很多工作,你可以使用另一个库来代替,比如json-iterator扩展jsontime

import "github.com/liamylian/jsontime"

var json = jsontime.ConfigWithCustomTimeFormat

type Book struct {
    Id        int           `json:"id"`
    UpdatedAt *time.Time    `json:"updated_at" time_format:"sql_date" time_utc:"true"`
    CreatedAt time.Time     `json:"created_at" time_format:"sql_datetime" time_location:"UTC"`
}
au9on6nz

au9on6nz3#

我在https://github.com/a-h/date编写了一个用于处理yyyy-MM-ddyyyy-MM-ddThh:mm:ss日期的包
它使用上面答案中的类型别名方法,然后通过一些修改实现MarshalJSONUnmarshalJSON函数。

// MarshalJSON outputs JSON.
func (d YYYYMMDD) MarshalJSON() ([]byte, error) {
    return []byte("\"" + time.Time(d).Format(formatStringYYYYMMDD) + "\""), nil
}

// UnmarshalJSON handles incoming JSON.
func (d *YYYYMMDD) UnmarshalJSON(b []byte) (err error) {
    if err = checkJSONYYYYMMDD(string(b)); err != nil {
        return
    }
    t, err := time.ParseInLocation(parseJSONYYYYMMDD, string(b), time.UTC)
    if err != nil {
        return
    }
    *d = YYYYMMDD(t)
    return
}

在正确的时区中进行解析是很重要的。我的代码假定使用UTC,但是出于某种原因,您可能希望使用计算机的时区。
我还发现,使用time.Parse函数的解决方案将Go语言的内部机制泄露为一条错误消息,而客户并不认为这有什么帮助,例如:cannot parse "sdfdf-01-01" as "2006"。只有当您知道服务器是用Go语言编写的,并且2006是示例日期格式时,这才有用,因此我添加了更可读的错误消息。
我还实现了Stringer接口,以便它在日志或调试消息中得到漂亮的打印。

omhiaaxx

omhiaaxx4#

封送、反封送和字符串方法的自定义实现。

package json

import (
    "fmt"
    "strings"
    "time"
)

const rfc3339 string = "2006-01-02"

// Date represents a date without a time component, encoded as a string
// in the "YYYY-MM-DD" format.
type Date struct {
    Year  int
    Month time.Month
    Day   int
}

// UnmarshalJSON implements json.Unmarshaler inferface.
func (d *Date) UnmarshalJSON(b []byte) error {
    t, err := time.Parse(rfc3339, strings.Trim(string(b), `"`))
    if err != nil {
        return err
    }
    d.Year, d.Month, d.Day = t.Date()
    return nil
}

// MarshalJSON implements json.Marshaler interface.
func (d Date) MarshalJSON() ([]byte, error) {
    s := fmt.Sprintf(`"%04d-%02d-%02d"`, d.Year, d.Month, d.Day)
    return []byte(s), nil
}

// String defines a string representation.
// It will be called automatically when you try to convert struct instance
// to a string.
func (d Date) String() string {
    return fmt.Sprintf("%04d-%02d-%02d", d.Year, d.Month, d.Day)
}

以及对他们的测试。

package json

import (
    "encoding/json"
    "testing"
    "time"
)

func TestDate_UnmarshalJSON(t *testing.T) {
    in := `"2022-12-31"`
    want := time.Date(2022, time.December, 31, 0, 0, 0, 0, time.UTC)

    var got Date
    if err := got.UnmarshalJSON([]byte(in)); err != nil {
        t.Fatalf("unexpected error: %v", err)
    }

    if !(got.Year == want.Year() && got.Month == want.Month() && got.Day == want.Day()) {
        t.Errorf("got date = %s, want %s", got, want)
    }
}

func TestDate_UnmarshalJSON_badFormat(t *testing.T) {
    in := `"31 Dec 22"`

    var got Date
    err := got.UnmarshalJSON([]byte(in))

    if err, ok := err.(*time.ParseError); !ok {
        t.Errorf("expected a time parse error, got: %v", err)
    }
}

func TestDate_MarshalJSON(t *testing.T) {
    testcases := map[string]struct {
        in   Date
        want string
    }{
        "without zero padding": {
            in:   Date{2022, time.December, 31},
            want: `"2022-12-31"`,
        },
        "with zero padding": {
            in:   Date{2022, time.July, 1},
            want: `"2022-07-01"`,
        },
        "initial value": {
            in:   Date{},
            want: `"0000-00-00"`,
        },
    }

    for name, tc := range testcases {
        t.Run(name, func(t *testing.T) {
            got, err := json.Marshal(tc.in)
            if err != nil {
                t.Fatalf("unexpected error: %v", err)
            }

            if string(got) != tc.want {
                t.Errorf("got date = %s, want %s", got, tc.want)
            }
        })
    }
}

func TestDate_String(t *testing.T) {
    testcases := map[string]struct {
        in   Date
        want string
    }{
        "without zero padding": {
            in:   Date{2022, time.December, 31},
            want: "2022-12-31",
        },
        "with zero padding": {
            in:   Date{2022, time.July, 1},
            want: "2022-07-01",
        },
        "initial value": {
            in:   Date{},
            want: "0000-00-00",
        },
    }

    for name, tc := range testcases {
        t.Run(name, func(t *testing.T) {
            if got := tc.in.String(); got != tc.want {
                t.Errorf("got %q, want %q", got, tc.want)
            }
        })
    }
}

相关问题