Golang XML Unmarshal 和 time.Time 字段 [英] Golang XML Unmarshal and time.Time fields

查看:34
本文介绍了Golang XML Unmarshal 和 time.Time 字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有通过 REST API 检索的 XML 数据,我将其解组到 GO 结构中.其中一个字段是日期字段,但是 API 返回的日期格式与默认时间不匹配.时间解析格式因此解组失败.

I have XML data I am retrieving via a REST API that I am unmarshal-ing into a GO struct. One of the fields is a date field, however the date format returned by the API does not match the default time.Time parse format and thus the unmarshal fails.

有什么方法可以指定 unmarshal 函数在 time.Time 解析中使用哪种日期格式?我想使用正确定义的类型并使用字符串来保存日期时间字段感觉不对.

Is there any way to specify to the unmarshal function which date format to use in the time.Time parsing? I'd like to use properly defined types and using a string to hold a datetime field feels wrong.

示例结构:

type Transaction struct {

    Id int64 `xml:"sequencenumber"`
    ReferenceNumber string `xml:"ourref"`
    Description string `xml:"description"`
    Type string `xml:"type"`
    CustomerID string `xml:"namecode"`
    DateEntered time.Time `xml:"enterdate"` //this is the field in question
    Gross float64 `xml:"gross"`
    Container TransactionDetailContainer `xml:"subfile"`
}

返回的日期格式为yyyymmdd".

The date format returned is "yyyymmdd".

推荐答案

我也遇到了同样的问题.

I had the same problem.

time.Time 不满足 xml.Unmarshaler 接口.而且您不能指定日期格式.

time.Time doesn't satisfy the xml.Unmarshaler interface. And you can not specify a date fomat.

如果您不想在之后处理解析并且更愿意让 xml.encoding 来处理,一种解决方案是创建一个带有匿名 time.Time<的结构/code> 字段并使用您的自定义日期格式实现您自己的 UnmarshalXML.

If you don't want to handle the parsing afterward and you prefer to let the xml.encoding do it, one solution is to create a struct with an anonymous time.Time field and implement your own UnmarshalXML with your custom date format.

type Transaction struct {
    //...
    DateEntered     customTime     `xml:"enterdate"` // use your own type that satisfies UnmarshalXML
    //...
}

type customTime struct {
    time.Time
}

func (c *customTime) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
    const shortForm = "20060102" // yyyymmdd date format
    var v string
    d.DecodeElement(&v, &start)
    parse, err := time.Parse(shortForm, v)
    if err != nil {
        return err
    }
    *c = customTime{parse}
    return nil
}

如果您的 XML 元素使用属性作为日期,则必须以相同的方式实现 UnmarshalXMLAttr.

If your XML element uses an attribut as a date, you have to implement UnmarshalXMLAttr the same way.

参见http://play.golang.org/p/EFXZNsjE4a

这篇关于Golang XML Unmarshal 和 time.Time 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆