-2

I have a simple function:

public JsonResult FetchData(object obj)
{
  var jsonData = new { dateTime = DateTime.Today };
  jsonData = JsonConvert.DeserializeAnonymousType(obj.ToString(), jsonData);
}

CASE A: If I use json data {"dateTime":"2018-09-24"} I can get right date: 2018-09-24

CASE B: If I use json data, variable name has a blank space {"dateTime ":"2018-09-24"} I get date: 0001-01-01, without any exception. "dateTime " is not a valid variable name for me

The behaviour I want is for CASE B to throw an exception or notice this case is invalid. How do I achieve that?

Thanks

Rock
  • 205
  • 1
  • 4
  • 14

1 Answers1

0

Use a proper data structure to deserialise and you can control the property names with the JsonProperty attribute:

public class Foo
{
    [JsonProperty("dateTime ")] //Note the space in here
    public DateTime DateTime { get; set; }
}

And now deserialise like this:

var result = JsonConvert.DeserializeObject<Foo>(json);
DavidG
  • 113,891
  • 12
  • 217
  • 223