0

In Postman, I'm sending the following JSON via a POST to API.

{
"id": "21",
"crgName": "Walgreens - 11/07/2018 - Standard ",
"crgStarteddatetime": "2018-11-07T10:11:10",
}

...but, I get the following error: FormatException: String was not recognized as a valid DateTime.

Inside my controller, I'm using DateTimeFormat to format the date time:

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

...is there an issue in my syntax as to how I have the Date formatted? My intentions are to formate the date as it is reflected in the JSON. Could I get some help as to what am I doing wrong?

Tetsuya Yamamoto
25.1k8 gold badges43 silver badges63 bronze badges
asked Nov 7, 2018 at 17:41

1 Answer 1

2

The problem lies in this line:

DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss.fff'Z'")

You're specifying the format exactly as UTC/Zulu datetime with 'Z' format specifier and 3 digits of seconds fraction (fff format specifier), but the value used in crgStarteddatetime doesn't have both of them (i.e. yyyy-MM-dd'T'HH:mm:ss).

Based on the JSON example, you should change the format to match exactly as provided in crgStarteddatetime:

var serializer = new DataContractJsonSerializer(obj.GetType(), new DataContractJsonSerializerSettings
 {
 DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss")
 });

If actual JSON data of crgStarteddatetime has mixed date formats (some of the dates have yyyy-MM-dd'T'HH:mm:ss and others may have yyyy-MM-dd'T'HH:mm:ss'Z'), use K format specifier which is more flexible to handle timezone format:

var serializer = new DataContractJsonSerializer(obj.GetType(), new DataContractJsonSerializerSettings
 {
 DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ssK")
 });
answered Nov 8, 2018 at 1:46
1
  • Thank you, I greatly appreciate your help Commented Nov 9, 2018 at 20:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.