0

So, I have a JSON object that contains dates where candidates completed their degree. The date formats aren't particularly standardized, and might consist only of the year that they completed their degree. I'm trying to deserialize this JSON using Newtonsoft, and I'm getting the following exception:

Exception reading JSON: Newtonsoft.Json.JsonReaderException: Could not convert string to DateTime: 2003

The exception message is pretty straightfoward: it doesn't recognize strings that consist only of the year as a valid DateTime.

Is there a way that I can fix this (e.g. by having this always deserialize to January 1 of the specified year), or am I stuck just having to make this field a string in my model class?

3 Answers3

4

when deserializing,

Deserialize the Year as an int and add another property that returns the full date.

something like:

public class MyObject
{
  [JsonProperty("year")]
  public int Year { get; set; }

  [JsonIgnore]
  public DateTime FullDate() {
     return new DateTime (this.Year, 1, 1, 0, 0, 0);
  } 
}
Mark Redman
  • 24,079
  • 20
  • 92
  • 147
2

DateTime is a structure that always contains an precise point in history. You might want to consider simply having a integer member for GraduationYear.

ebol2000
  • 1,195
  • 11
  • 16
1

If the input json can be different formats, you can always implement your own JsonConverter that handles the logic you want.

How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects? has some examples how to do that. It's a little more verbose, but gives you full control of how you deserialize the data.

ryzngard
  • 136
  • 7