UnmarshalJSON 的结构组合 [重复]

问题描述 投票:0回答:0

我有一个具有不同时间格式的 json,所以我想要一个由不同时间结构组成的基类。 我的主要目标是拥有一个 BaseDate,我可以在其中使用不同的时间格式编组和取消编组。所以当我面临这个问题时,我做了这个结构

type BaseDate struct {
    time.Time
    DateFormat string
}

func (b *BaseDate) MarshalJSON() ([]byte, error) {
    //do your serializing here
    stamp := fmt.Sprintf("\"%s\"", b.Format(b.DateFormat))
    return []byte(stamp), nil
}

func (b *BaseDate) UnmarshalJSON(data []byte) error {
    // Ignore null, like in the main JSON package.
    str := strings.Trim(string(data), "\"")
    if str == "null" || str == "" {
        return nil
    }
    tt, err := time.Parse(b.DateFormat, str)
    b.Time = tt
    return err
}

我尝试制作其他结构,但我无法覆盖 BaseDate 中 DateFormat 的默认值。

type JSONDateTime struct {
    Time.BaseDate
    DateFormat string `default:"2006-01-02T15:04:05"`
}

func NowDateTime() JSONDateTime {
    return JSONDateTime{
        BaseDate: Time.Now(),
    }
}

type JSONDate struct {
    Time.BaseDate
    DateFormat string `default:"2006-01-02"`
}

func NowDate() JSONDate {
    return JSONDate{
        BaseDate: Time.Now(),
    }
}

我的主要 Json 结构看起来像这样

type Etichetta struct {
    DateTimeCreate  JSONDateTime    `json:"DateTimeCreate"`
    DateStart       JSONDate        `json:"DateStart"`

一个解决方案是覆盖 MarshalJSON 和 UnmarshalJSON 但我想避免这种情况。

json go composite go-fiber
© www.soinside.com 2019 - 2024. All rights reserved.