[英]ASP.NET Controller FormatException: String was not recognized as a valid DateTime
在Postman中,我通過POST將以下JSON發送到API。
{
"id": "21",
"crgName": "Walgreens - 11/07/2018 - Standard ",
"crgStarteddatetime": "2018-11-07T10:11:10",
}
...但是,出現以下錯誤: FormatException:無法將字符串識別為有效的DateTime。
在控制器內部,我正在使用DateTimeFormat格式化日期時間:
public static RemoteContextType DeserializeJsonString<RemoteContextType>(string jsonString)
{
//create an instance of generic type object
RemoteContextType obj = Activator.CreateInstance<RemoteContextType>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
var serializer = new DataContractJsonSerializer(obj.GetType(),
new DataContractJsonSerializerSettings
{
DateTimeFormat = new
DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss.fff'Z'")
});
obj = (RemoteContextType)serializer.ReadObject(ms);
ms.Close();
return obj;
}
...我的語法中是否有關於日期格式的問題? 我的意圖是格式化日期,因為它反映在JSON中。 我做錯了什么可以幫助我嗎?
問題出在這一行:
DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss.fff'Z'")
您正在使用'Z'
格式說明符和3位秒分數( fff
格式說明符 )來指定與UTC / Zulu日期時間完全相同'Z'
格式,但是crgStarteddatetime
中使用的值沒有兩者(即yyyy-MM-dd'T'HH:mm:ss
)。
根據JSON示例,您應該更改格式以完全匹配crgStarteddatetime
提供的crgStarteddatetime
:
var serializer = new DataContractJsonSerializer(obj.GetType(), new DataContractJsonSerializerSettings
{
DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss")
});
如果crgStarteddatetime
實際JSON數據具有混合的日期格式(某些日期具有yyyy-MM-dd'T'HH:mm:ss
而其他日期則具有yyyy-MM-dd'T'HH:mm:ss'Z'
) ,請使用K
格式說明符 ,它更靈活地處理時區格式:
var serializer = new DataContractJsonSerializer(obj.GetType(), new DataContractJsonSerializerSettings
{
DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ssK")
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.