简体   繁体   English

字符串未被识别为有效的DateTime(有效的UTC格式)

[英]String was not recognized as a valid DateTime (valid UTC format)

I'm trying to deserialize an XML object with the following node: 我正在尝试使用以下节点反序列化XML对象:

<startTime>2012-03-19T11:31:03.000Z</startTime>
<endTime>2012-03-19T11:31:03.000Z</endTime>

Those are the properties on the class which I use to deserialize the XML into: 这些是我用来将XML反序列化为类的属性:

[System.Xml.Serialization.XmlElementAttribute(DataType = "date", ElementName = "startTime")]
public DateTime StartTime { get; set; }

[System.Xml.Serialization.XmlElementAttribute(DataType = "date", ElementName = "endTime")]
public DateTime EndTime { get; set; }

Finally, this is the code I use to deserialize the XML: 最后,这是我用来反序列化XML的代码:

Stream resultStream = await response.Content.ReadAsStreamAsync();
var serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(resultStream) as T;

However, the code will throw an Exception, telling me that the string was not recognized as a valid DateTime object - with a base exception saying that the XML file has errors at (1,1926) which points directly to the two timestamps. 但是,代码将抛出一个Exception,告诉我该字符串未被识别为有效的DateTime对象 - 有一个基本异常,即XML文件在(1,1926)处有错误,它直接指向两个时间戳。

All I can seem to find regarding this error message is caused by incorrect usage of formats (ie wrong special characters used in the date string). 我似乎发现有关此错误消息的所有信息都是由于格式的错误使用(即日期字符串中使用的错误特殊字符)引起的。 However, in my case, the format seems to comply 100% with the MSDN description. 但是,就我而言,格式似乎符合MSDN描述的100%。

Can anybody help me to point out the mistake? 任何人都可以帮我指出错误吗?

Try using the "dateTime" DataType in your attributes - (watch the case: starting with a small d ): 尝试在属性中使用"dateTime" DataType - (观察案例:从小d ):

[System.Xml.Serialization.XmlElementAttribute(DataType = "dateTime", ElementName = "startTime")]
public DateTime StartTime { get; set; }

[System.Xml.Serialization.XmlElementAttribute(DataType = "dateTime", ElementName = "endTime")]
public DateTime EndTime { get; set; }

You are trying to Deserialize a DateTime using the Time format which can't work. 您正在尝试使用无法工作的Time格式反序列化DateTime But you don't get an error message at compilation because the DataType is a string. 但是在编译时没有收到错误消息,因为DataType是一个字符串。

You should try: 你应该试试:

[System.Xml.Serialization.XmlElementAttribute(DataType = "dateTime", ElementName = "startTime")]
public DateTime StartTime { get; set; }

[System.Xml.Serialization.XmlElementAttribute(DataType = "dateTime", ElementName = "endTime")]
public DateTime EndTime { get; set; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM