日期时间为MM/dd/yyyy HH:mm:ss时的JSON反序列化问题

6l7fqoea  于 2022-12-24  发布在  其他
关注(0)|答案(2)|浏览(106)

我有一个JSON,其日期时间格式为MM/dd/yyyy HH:mm:ss,例如12/20/2000 10:30:00。
完整的JSON将与此类似。

[
    {
        "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"
    }
]

我有一个带有id,name和date的c#类,其中date是一个DateTime类型。我试图将JSON对象转换为对象列表,我得到了如下所示的转换错误。

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

如果我把日期从类中删除,一切都正常。
如果我将日期转换为字符串类型,它就可以工作。但是我需要将它保留为DateTime。

zzwlnbp8

zzwlnbp81#

您可以使用需要提供JsonConverter的DateTime属性来完成此操作。

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" });

反序列化对象声明:

/// <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);
}

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

vecaoik1

vecaoik12#

这对我有用

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; }
}

相关问题