-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

2
  • Avoid CASE B by not having identifiers with spaces in them! Commented Sep 25, 2018 at 9:59
  • I add an additional check "jsonData.dateTime<new DateTime(2010,1,1)" to avoid the invalid data. Commented Nov 30, 2018 at 2:21

1 Answer 1

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

2 Comments

I want CASE B throw an exception
That's not what your question says.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.