简体   繁体   中英

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

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); }
}

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 ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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