Home > Back-end >  JSON Deserialization issue with DateTime in MM/dd/yyyy HH:mm:ss
JSON Deserialization issue with DateTime in MM/dd/yyyy HH:mm:ss

Time:12-24

I am having a JSON with a date time in MM/dd/yyyy HH:mm:ss format, for example 12/20/2000 10:30:00.

The complete JSON will be something similar to this.


[
    {
        "id": 10001,
        "name": "Name 1",
        "date": "10/01/2022 00:00:00"
    },
    {
        "id": 10002,
        "name": "Name 2",
        "date": "10/01/2022 00:00:00"
    },
    {
        "id": 10003,
        "name": "Name 3",
        "date": "10/01/2022 00:00:00"
    }
]

I have a c# class with id, name and date where date is a DateTime type. I am trying to convert the JSON object to a list of Object, I am getting a conversion error as shown below.

System.AggregateException: One or more errors occurred. (Unable to deserialize response content to the type of List`1)\r\n ---> System.Exception: Unable to deserialize response content to the type of List`1\r\n

If I remove the date from the class, everything works fine.

If I convert the date to a string type, it works. But I need to keep it as DateTime.

CodePudding user response:

you can do this, with DateTime properties you need to provide the JsonConverter.

public class Root
{
    public int id { get; set; }
    public string name { get; set; }
    public DateTime date { get; set; }
}

var ls = JsonConvert.DeserializeObject<List<Root>>(content, new IsoDateTimeConverter { DateTimeFormat = "MM/dd/yyyy HH:mm:ss" });

DeserializeObject Declaration:

/// <summary>
/// Deserializes the JSON to the specified .NET type using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static T? DeserializeObject<T>(string value, params JsonConverter[] converters)
{
    return (T?)DeserializeObject(value, typeof(T), converters);
}

Reference: https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_Converters_IsoDateTimeConverter_DateTimeFormat.htm

CodePudding user response:

this works for me

var jsonSettings = new JsonSerializerSettings { DateFormatString = "dd/MM/yyyy hh:mm:ss" };
    
List<Data> data = JsonConvert.DeserializeObject<List<Data>>(json, jsonSettings);

public class Data
{
    public int id { get; set; }
    public string name { get; set; }
    public DateTime date { get; set; }
}
  • Related