26

This JsonSerializationException was thrown when I tried to input the following DateTime parameters in my Json :

"Error converting value {null} to type 'System.DateTime' in input json"

I have given the input here :

string inputJSONString = "{....,\"StartDateFrom\":null,\"StartDateTo\":null,\"EndDateFrom\":null,\"EndDateTo\":null,\....}";

and deserialising using :

scT = (SearchCriteriaTask)JsonConvert.DeserializeObject(inputJSONString , typeof(SearchCriteriaTask));

My json is correct , and I have also tried ("") values instead of null. I was not able to find proper solution elsewhere. Thanks.

If any part of code is needed, then please mention it.

bcesars
  • 1,016
  • 1
  • 17
  • 36
Atif Qadri
  • 462
  • 1
  • 5
  • 15

1 Answers1

61

As the error is trying to tell you, .Net value types like DateTime cannot hold nulls.

If you want to allow nulls, use nullable types:

DateTime? StartDateFrom { get; set; }
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 2
    I now have come to know about how basic this problem was ! i had no idea it used a nullable like this. I am very new to it. this worked. Thanks – Atif Qadri Sep 02 '13 at 09:30
  • 1
    If someone has the question as to why DateTime can't be null, that answer can be found here: http://stackoverflow.com/questions/689512/why-is-null-not-allowed-for-datetime-in-c – Francisco d'Anconia Jan 19 '16 at 19:38