”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在 Go 中自定义解组非标准 JSON 时间格式?

如何在 Go 中自定义解组非标准 JSON 时间格式?

发布于2024-12-23
浏览:471

How to Custom Unmarshal Non-Standard JSON Time Formats in Go?

非标准 JSON 时间格式的自定义取消/编组

处理包含非标准格式时间值的 JSON 数据时,内置 JSON 解码器可能会遇到错误。为了处理这种情况,可以实现自定义编组和解组函数。

考虑以下 JSON:

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

以及所需的 Go 结构:

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

使用标准 JSON 解码器在解析“birth_date”字段时会导致错误。要自定义此行为,可以创建类型别名并将其添加到结构中:

type JsonBirthDate time.Time

然后,实现自定义编组和解组函数:

func (j *JsonBirthDate) UnmarshalJSON(b []byte) error {
    s := strings.Trim(string(b), `"`) // Remove quotes
    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))
}

通过这些自定义函数,现在可以将 JSON 解码为 Go 结构体:

person := Person{}

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

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

// Print the birth date using the Format function
fmt.Println(person.BirthDate.Format("2006-01-02"))
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3