亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Go 中將自定義格式的時間序列化為 xml 或從 xml 序列化?

如何在 Go 中將自定義格式的時間序列化為 xml 或從 xml 序列化?

Go
慕標琳琳 2021-10-18 11:04:33
將日期時間序列化為 xml 時,如何使其使用自定義時間格式?
查看完整描述

2 回答

?
萬千封印

TA貢獻1891條經驗 獲得超3個贊

就像您使用 JSON實現json.Marshaler和json.Unmarshaler執行此操作一樣(在 StackOverflow 和互聯網上有很多關于此的帖子);一種方法是實現實現encoding.TextMarshaler和的自定義時間類型encoding.TextUnmarshaler。


這些接口encoding/xml在對項目進行編碼時使用(在首先檢查更具體的xml.Marshaler或xml.Unmarshaler接口之后,但是后來的那些必須自己進行完整的 XML 編碼)。


例如類似(完整示例Go Playground):


const fixedFormat = "Mon Jan 02 2006"


type myTime1 struct {

    time.Time

}


func (m myTime1) MarshalText() ([]byte, error) {

    text := m.Time.Format(fixedFormat)

    return []byte(text), nil

}

func (m *myTime1) UnmarshalText(text []byte) error {

    t, err := time.Parse(fixedFormat, string(text))

    if err == nil {

        m.Time = t

    }

    return err

}

或者


type myTime2 time.Time


func (m myTime2) MarshalText() ([]byte, error) {

    text := time.Time(m2).Format(fixedFormat)

    return []byte(text), nil

}

func (m *myTime2) UnmarshalText(text []byte) error {

    t, err := time.Parse(fixedFormat, string(text))

    if err == nil {

        *m = myTime2(t)

    }

    return err

}

這些中的任何一個都可以用來代替time.Time與 xml (un) marshalling 一起使用的更大數據結構的一部分。例如:


type Foo struct {

    Date1 myTime1 `xml:"date1"`

    Date2 myTime2 `xml:"date2"`

}

這些自定義時間類型定義方式的不同會改變您將它們與常規time.Time值一起使用的方式。例如


m1 := myTime1{time.Now()}

fmt.Println(m1)

if m1.Before(time.Now()) {}

t1 := m1.Time

// compared to:

m2 := myTime2(time.Now())

fmt.Println(time.Time(m2))

if time.Time(m2).Before(time.Now()) {}

t2 := time.Time(m2)


查看完整回答
反對 回復 2021-10-18
  • 2 回答
  • 0 關注
  • 216 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號