简体   繁体   中英

Parse custom JSON string to DateTime Convert in API

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM