首页 > 解决方案 > 我可以指定需要 JsonReader 转换为 DateTime 的字段的当前格式吗?

问题描述

我正在开发一个程序,将 JSON 数据反序列化为自定义类的列表,然后将其全部上传到我的 SQL Server。

string json = streamReader.ReadToEnd();
JObject jsonEntriesRaw = JsonConvert.DeserializeObject( json ) as JObject;
JArray jsonEntries = jsonEntriesRaw[ "events" ] as JArray; //since the data i actually need is wrapped in "events"
List<MoveUpdateEntry> entries = jsonEntries.ToObject<List<MoveUpdateEntry>>(); //error occurs here

我的自定义类...

public class MoveUpdateEntry
{
    public DateTime errorCreateDate { get; set; }
}

...有一个(Sql?)DateTime 字段,我不知道如何正确解析数据。

我面临的问题是程序不了解如何使用我正在处理的特定日期格式(yyyyMMdd hh:mm:ss)。

Unhandled Exception: Newtonsoft.Json.JsonReaderException: Could not convert string to DateTime: 20200630 18:19:01. Path 'events[0].errorCreateDate'.

我怎样才能JsonReader知道预期的格式类型?

标签: c#jsonjson.net

解决方案


您缺少一个简单的DateTime解析。

你能试试这个吗?

List<MoveUpdateEntry> entries = jsonEntries
                                .ToObject<List<string>>() // replace string with the expected type.
                                .Select(x => new MoveUpdateEntry{
                                    errorCreateDate = DateTime.ParseExact(x, "yyyyMMdd HH:mm:ss", null)
                                })
                                .ToObject<List<MoveUpdateEntry>>();

推荐阅读