Dar*_*ren 19 go unmarshalling xml-parsing
我有通过REST API检索的XML数据,我正在解组为GO结构.其中一个字段是日期字段,但API返回的日期格式与默认的time.Time解析格式不匹配,因此unmarshal失败.
有没有办法指定unmarshal函数在time.Time解析中使用哪种日期格式?我想使用正确定义的类型,并使用字符串来保存日期时间字段感觉不对.
示例结构:
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"`
}
Run Code Online (Sandbox Code Playgroud)
返回的日期格式为"yyyymmdd".
rou*_*ied 52
我有同样的问题.
time.Time不满足xml.Unmarshaler界面.而且您无法指定日期格式.
如果你不想在之后处理解析而你更愿意xml.encoding这样做,一个解决方案是创建一个带有匿名time.Time字段的结构,并UnmarshalXML使用自定义日期格式实现自己的结构.
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
}
Run Code Online (Sandbox Code Playgroud)
如果您的XML元素使用attribut作为日期,则必须以相同的方式实现UnmarshalXMLAttr.
见http://play.golang.org/p/EFXZNsjE4a
| 归档时间: |
|
| 查看次数: |
9143 次 |
| 最近记录: |