You need to enable JavaScript to run this app. Go语言JSON序列化支持多种自定义时间格式的实现方案咨询
优惠活动
大模型
产品
解决方案
定价
更多

Go语言JSON序列化支持多种自定义时间格式的实现方案咨询

可行实现方案

Go标准库encoding/json的自定义序列化逻辑依赖类型方法实现,无法在方法内部获取当前结构体字段的Tag配置,因此通过Tag传格式的方案不可行。最优方案是抽离公共逻辑,新增毫秒级时间类型,仅需加少量代码即可实现,无需重复编写整套逻辑。


第一步:重构utils包抽离公共逻辑

基础版实现

把和格式无关的逻辑、可复用的序列化/反序列化逻辑抽成通用函数,新增格式仅需新增对应类型:

package utils

import (
    "database/sql/driver"
    "fmt"
    "strings"
    "time"
)

var nilTime = (time.Time{}).UnixNano()

// 通用JSON反序列化逻辑
func unmarshalTime(b []byte, layout string) (time.Time, error) {
    s := strings.Trim(string(b), "\"")
    if s == "null" {
        return time.Time{}, nil
    }
    return time.Parse(layout, s)
}

// 通用JSON序列化逻辑
func marshalTime(t time.Time, layout string) ([]byte, error) {
    if t.UnixNano() == nilTime {
        return []byte("null"), nil
    }
    return []byte(fmt.Sprintf("\"%s\"", t.Format(layout))), nil
}

// 通用判断是否设置值
func isTimeSet(t time.Time) bool {
    return t.UnixNano() != nilTime
}

// 原有日期格式时间类型
type CustomTime struct {
    time.Time
}

const ctLayout = "2006-01-02"

func (ct *CustomTime) UnmarshalJSON(b []byte) (err error) {
    ct.Time, err = unmarshalTime(b, ctLayout)
    return
}

func (ct *CustomTime) MarshalJSON() ([]byte, error) {
    return marshalTime(ct.Time, ctLayout)
}

func (ct *CustomTime) IsSet() bool {
    return isTimeSet(ct.Time)
}

func (c CustomTime) Value() (driver.Value, error) {
    return driver.Value(c.Time), nil
}

func (c *CustomTime) Scan(src interface{}) error {
    switch t := src.(type) {
    case time.Time:
        c.Time = t
        return nil
    default:
        return fmt.Errorf("column type not supported")
    }
}

// 新增带毫秒的时间类型
type CustomTimeMS struct {
    time.Time
}

const ctMSLayout = "2006-01-02 15:04:05.000"

func (ct *CustomTimeMS) UnmarshalJSON(b []byte) (err error) {
    ct.Time, err = unmarshalTime(b, ctMSLayout)
    return
}

func (ct *CustomTimeMS) MarshalJSON() ([]byte, error) {
    return marshalTime(ct.Time, ctMSLayout)
}

func (ct *CustomTimeMS) IsSet() bool {
    return isTimeSet(ct.Time)
}

func (c CustomTimeMS) Value() (driver.Value, error) {
    return driver.Value(c.Time), nil
}

func (c *CustomTimeMS) Scan(src interface{}) error {
    switch t := src.(type) {
    case time.Time:
        c.Time = t
        return nil
    default:
        return fmt.Errorf("column type not supported")
    }
}

进阶优化(进一步减少重复代码)

如果后续可能新增更多时间格式,可以把格式无关的逻辑封装到基础结构体,新增格式仅需实现两个序列化方法:

// 基础时间结构体,封装所有格式无关的逻辑
type BaseCustomTime struct {
    time.Time
}

func (b *BaseCustomTime) IsSet() bool {
    return isTimeSet(b.Time)
}

func (b BaseCustomTime) Value() (driver.Value, error) {
    return driver.Value(b.Time), nil
}

func (b *BaseCustomTime) Scan(src interface{}) error {
    switch t := src.(type) {
    case time.Time:
        b.Time = t
        return nil
    default:
        return fmt.Errorf("column type not supported")
    }
}

// 日期格式类型,仅需实现序列化/反序列化
type CustomTime struct {
    BaseCustomTime
}

func (ct *CustomTime) UnmarshalJSON(b []byte) (err error) {
    ct.Time, err = unmarshalTime(b, ctLayout)
    return
}

func (ct *CustomTime) MarshalJSON() ([]byte, error) {
    return marshalTime(ct.Time, ctLayout)
}

// 毫秒格式类型,仅需实现序列化/反序列化
type CustomTimeMS struct {
    BaseCustomTime
}

func (ct *CustomTimeMS) UnmarshalJSON(b []byte) (err error) {
    ct.Time, err = unmarshalTime(b, ctMSLayout)
    return
}

func (ct *CustomTimeMS) MarshalJSON() ([]byte, error) {
    return marshalTime(ct.Time, ctMSLayout)
}

第二步:结构体中使用对应类型

需要日期格式的字段继续用CustomTime,需要毫秒格式的字段改用CustomTimeMS即可,原有业务逻辑完全兼容:

type Entry struct {
    ID                int                `json:"id"`
    AuthorisedBy      string             `json:"authorisedBy"`
    Duid              string             `json:"duid"`
    IntervalCount     int32              `json:"intervalCount"`
    Intervals         []int32            `json:"intervals"`
    RequestId         string             `json:"requestId"`
    // 带毫秒的时间字段改用CustomTimeMS
    RequestTimestamp  utils.CustomTimeMS `json:"requestTimestamp"`
    TradingDate       utils.CustomTime   `json:"tradingDate"`
    Unit              string             `json:"unit"`
    RebidExplanation  string             `json:"rebidexplanation"`
    AcceptedTimestamp time.Time          `json:"acceptedTimestamp"`
}

方案优势

  • 原有代码完全兼容,不需要修改已有的CustomTime相关业务逻辑
  • 重复代码极少,后续新增其他时间格式仅需十几行代码即可完成
  • 保留了原有的数据库读写能力,和原有业务适配逻辑一致

内容的提问来源于stack exchange,提问作者Peter Nunn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 21:09:00