c# XML deserialize list of time string to list DateTime bject

自古美人都是妖i 提交于 2019-12-12 00:55:41

问题


I'm having some trouble wrapping my head around this one. Im returning a bunch of xml from an API call (which i have no control over).The data looks like this but with many more entries.

`<time>10:00:00</time>
 <go>true</go>
 <time>10:30:00</time>
 <go>false</go>
`

I can deserialize it fine into a list two lists of strings List<string> time and list<string> go

However i really need that time to be deserialized into a datetime object. Right now i have the following working but only for a single instance but not for a list. Im having trouble with the getter and setter no doubt

[XmlIgnore]
public List<DateTime> DoNotSerialize { get; set; }
[XmlElement("time")]
public List<string> time
{
     get { return DoNotSerialize.ToString("HH:MM:SS") }
     set { DoNotSerialize = DateTime.Parse(value); }
}

回答1:


Try using this:

[XmlIgnore]
public List<DateTime> DoNotSerialize { get; set; }
[XmlElement("time")]        
public List<string> time
{
    get { return DoNotSerialize.Select(item => item.ToString("yyyy-MM-dd")).ToList(); }
    set { DoNotSerialize = value.Select(item => DateTime.Parse(item)).ToList(); }
}

(I had a similar problem days ago, but with serialization instead of deserialization. If you're interested, check my previous SO question...)



来源:https://stackoverflow.com/questions/22581109/c-sharp-xml-deserialize-list-of-time-string-to-list-datetime-bject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!