此代碼:DateTime的WebApi序列化 - 如何反序列化?
public class PhotoDescriptor
{
public DateTime DateCreatedUtc { get; set; }
}
public class PhotosController : ApiController
{
// GET api/photos
public IEnumerable<PhotoDescriptor> GetListOfPhotos()
{
return new PhotoDescriptor[]
{
new PhotoDescriptor
{
DateCreatedUtc = DateTime.ParseExact(
"2012-07-24T00:28:41.8738770Z",
"o",
CultureInfo.InvariantCulture,
DateTimeStyles.None).ToUniversalTime(),
},
new PhotoDescriptor
{
DateCreatedUtc = DateTime.ParseExact(
"2012-07-24T00:28:41.0000000Z",
"o",
CultureInfo.InvariantCulture,
DateTimeStyles.None).ToUniversalTime(),
},
};
}
返回以下JSON:
[{"DateCreatedUtc":"2012-07-24T00:28:41.873877Z"},
{"DateCreatedUtc":"2012-07-24T00:28:41Z"}]
通知,尾隨零,從日期時間除去。但是,當我試圖解析這些字符串,讓我的日期時間回來,我得到FormatException - String was not recognized as a valid DateTime
:
var date = DateTime.ParseExact("2012-07-24T00:28:41.873877Z", "o", CultureInfo.InvariantCulture, DateTimeStyles.None);
這是正確的,根據MSDN DateTime.ParseExact Method:
出現FormatException
s不包含與格式指定的格式 相對應的日期和時間。
和"o"
格式is defined如下:
YYYY ' - ' MM ' - ' dd'T'HH。' ':' 毫米 '' SS fffffffK
所以清楚地顯示尾隨零應該在那裏。
這是WebApi中的錯誤,還是我做錯了什麼?我應該如何將日期/時間字段傳遞給我的.Net客戶端?
謝謝。