1

I want to deserialize the JSON String

    {\"entityType\":\"Phone\",\"countValue\":30,\"lastUpdateDate\":\"3/25/14 12:00:00 PM MST\",\"RowCnt\":30}.

But I am getting

JSONReaderException "Could not convert string to DateTime: 3/25/14 12:00:00 PM MST".

Note: We are using Newtonsoft.JSON for serialize/deserialize.

Neha Shukla
  • 3,572
  • 5
  • 38
  • 69
  • possible duplicate of [Parsing JSON DateTime from Newtonsoft's JSON Serializer](http://stackoverflow.com/questions/668488/parsing-json-datetime-from-newtonsofts-json-serializer) – Timothy Groote Jun 12 '15 at 06:31
  • Actually this one seems closer: http://stackoverflow.com/questions/21256132/deserializing-dates-with-dd-mm-yyyy-format-using-json-net – dbc Jun 12 '15 at 06:40
  • Here my string is 3/25/14 12:00:00 PM MST. This is not de serializing properly. We are having MST string in the date time – karthikeyan Jun 12 '15 at 06:57

1 Answers1

1

This is actually slightly more complicated than the suggested duplicates. Here's a related question that deals with parsing strings that contain time zone abbreviations.

To use the information in that answer with JSON.NET, you might be best off using a custom converter:

public class DateTimeWithTimezoneConverter : JsonConverter
{
    public override object ReadJson(
        JsonReader reader,
        Type objectType,
        object existingValue,
        JsonSerializer serializer)
    {
        string t = serializer.Deserialize<string>(reader);

        t = t.Replace("MST", "-07:00");
        // Do other replacements that you need here.

        return 
            DateTime.ParseExact(t, @"M/dd/yy h:mm:ss tt zzz", CultureInfo.CurrentCulture);
    }

    public override void WriteJson(
        JsonWriter writer,
        object value,
        JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }    


    public override bool CanConvert(Type t)
    {
        return typeof(DateTime).IsAssignableFrom(t);
    }
}

Note that this only handles the specific case you presented in your question. If you need support for more time zones, check the linked answer. If you have control over the code generating the strings, you might want to use an offset instead of a time zone abbreviation.

Here's an example of how you'd use it:

public class MyType
{
    public string EntityType { get; set; }
    public int CountValue { get; set; }
    public DateTime LastUpdateDate { get; set; }
    public int RowCnt { get; set; }
}

 string json = "{\"entityType\":\"Phone\",\"countValue\":30,\"lastUpdateDate\":\"3/25/14 12:00:00 PM MST\",\"RowCnt\":30}";

 MyType obj = JsonConvert.DeserializeObject<MyType>(
    json,
    new DateTimeWithTimezoneConverter());
Community
  • 1
  • 1
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307