0

I'm using a JObject to handle my client post's.
I convert the JObject into a strong type entity using the ToObject function.

When the datetime value isn't valid - let's say 29\05\2014(since there aren't 29 months), I get an exception:

Could not convert string to DateTime: 29/05/2014. Path 'PurchaseDate.Value'.

I understand the exception and I would like to prevent crashes in those kind of situations.

How can I tell the JObject to ignore invalid date values? In my specific case my entity is a nullable datetime object so I would like to keep in null if the parsing fails(rather then crash).

In this specific case I'm talking about a datetime, but if someone can give me a more generic answer on how I can prevent failures on "invalid parsing\conversions" that would be great, since all of my entities contain nullable fields and I don't want to handle validations on the client side.

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99

2 Answers2

1

You cannot disable them just for invalid dates, but you can stop the parsing of date values, storing them as strings and implement a custom parsing later.

jObject.ToObject<MyObject>(  new JsonSerializer {
                          DateParseHandling = DateParseHandling.None
                   });
nsgocev
  • 4,390
  • 28
  • 37
  • Hi, I know about this feature and I can't just change my datetimes to strings since I need backward compatibility for older systems that use the same entities. Do you know a way to tell him to use something like 'TryParse' instead of 'Parse'? – Amir Popovich Jul 03 '14 at 09:32
  • You will probably need to implement a custom json serializer. There is an example here http://stackoverflow.com/questions/17856580/newtonsoft-json-custom-serialization-behavior-for-datetime – nsgocev Jul 03 '14 at 10:37
1

I found a work around - Adding a converter:

   var js = new JsonSerializer
   {
       DateParseHandling = DateParseHandling.DateTime,
   };
   js.Converters.Add(new DateTimeConverter());

   dynamic jsonObject = new JObject();
   jsonObject.Date = "29/05/2014";
   var entty = ((JObject)jsonObject).ToObject<Entity>(js);

Definitions:

    public class Entity
    {
        public DateTime? Date { get; set; }
    }

    public class DateTimeConverter : DateTimeConverterBase
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            DateTime val;
            if (reader.Value != null && DateTime.TryParse(reader.Value.ToString(), out val))
            {
                return val;
            }

            return null;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue(((DateTime)value).ToString("MM/dd/yyyy"));
        }
    }
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99