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?

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")
                 });
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I greatly appreciate your help

Your Answer

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.