Exception occurs while deserialize json containing date with different format C#

Having json string containing date field

{
  "totalSize": 2,
  "records": [
    {
      "Id": "5006C000008ZhEDQA0",
      "CreatedDate": "2021-12-01T15:14:20.000+0000",
      "CaseNumber": "01378682",
      "Status": "Open"
    },
    {
      "Id": "5006C000008ZhE00A0",
      "CreatedDate": "2021-12-05T08:00:00.000+0000",
      "CaseNumber": "01378692",
      "Status": "Open"
    }
  ]
}

I'm trying to do normal Deserialization where CreatedDate datatype is DateTime.

JsonSerializer.Deserialize<SFHistoryResponse>(stringResponse);

I'm getting

The JSON value could not be converted to System.DateTime. Path: $.records[0].CreatedDate

is there any way to format JSON's date part before Deserialization


Solution 1:

The Newtonsoft JSON library can deserialize the string properly without throwing an exception:

using Newtonsoft.Json;

var response =  JsonConvert.DeserializeObject<SFHistoryResponse>(stringResponse);

Solution 2:

In your case your classes need to be:

  public class Record
{
    public string Id { get; set; }
    public DateTime CreatedDate { get; set; }
    public string CaseNumber { get; set; }
    public string Status { get; set; }
}

public class SFHistoryResponse
{
    public int totalSize { get; set; }
    public List<Record> records { get; set; }
}

and when you try to deserialize the json

SFHistoryResponse l = JsonConvert.DeserializeObject<SFHistoryResponse>(jsonString);

tested my self

tbResult.Text = "l.records[0].CreatedDate.ToString() - " + l.records[0].CreatedDate.ToString();

enter image description here