-1

My Question is similar to this one (The JSON value could not be converted to System.DateTime), where I am trying to convert an input string to an DateTime. The difference, however, is that the input string cannot be changed. I have no choice in it.

[HttpPut("PutBodyToFoodChain")]
public async Task<IActionResult> PutBodyToFoodChain([FromBody] TxMSAGrading body)
{ ... }

What I've tried:

[JsonConverter(typeof(DateFormatConverter), "MM/dd/yyyy hh:mm:ss")]
public DateTime KillDate { get; set; }

Error:

The JSON value could not be converted to System.DateTime

Input String:

{"GradeDate": "08/24/2020 01:36:00", "KillDate" : "08/24/2020 00:00:00", ... }

Additional Information:

  • I cannot change the model. So it will always be parsed in to be converted to a Date-Time.
  • There are 500+ fields in the model. I can't explicitly convert every Date-time field.
  • DateTime fields will always have the same format.
Cornelis
  • 1,065
  • 8
  • 23

1 Answers1

0

One idea is to defer parsing until after the raw string is captured in your model. This allows deserialization to succeed more reliably and for you to have control over the parsing. For example, an updated model:

public string KillDate { get; set; }

public DateTime KillDateValue => DateTime.TryParse(KillDate, out DateTime parsed) ? parsed : DateTime.MinValue;

public bool KillDateParsed => KillDateValue != DateTime.MinValue;

If parsing succeeds, KillDateParsed will be true and you'll have the parsed value in KillDateValue. DateTime.TryParse can also be provided a specific pattern to match.

Noah Stahl
  • 6,905
  • 5
  • 25
  • 36
  • Not an option for two reasons: Using a nuget package for models employed company wide. Changing the model can have company wide ramifications. I suppose writing middleware to intercept the JSON is an option. The Second reason being the models are quite large. 500+ variables. I don't want to explicitly convert each them. – Cornelis Jul 30 '20 at 22:34
  • Hmm, well I'd still at least use a different DTO model in between that you can control, and use AutoMapper if needed to get values back and forth. – Noah Stahl Jul 31 '20 at 01:56