0

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

2 Answers 2

1

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

using Newtonsoft.Json;

var response =  JsonConvert.DeserializeObject<SFHistoryResponse>(stringResponse);
Sign up to request clarification or add additional context in comments.

4 Comments

same thing i did.. and its throwing error as date format in json is "2021-12-05T08:00:00.000+0000" and it wont work
i did trick by replacing ".000+0000" with "" before deserialization but its marked as in appropriate
You're using the deserializer out of System.Text.Json. It isn't the same.
ohh my bad, i will try this right away
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.