反序列化包含不同格式 C# 的日期的 json 时发生异常
Exception occurs while deserialize json containing date with different format C#
具有 json 个包含日期字段的字符串
{
"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"
}
]
}
我正在尝试进行正常的反序列化,其中 CreatedDate 数据类型是 DateTime。
JsonSerializer.Deserialize<SFHistoryResponse>(stringResponse);
我得到
The JSON value could not be converted to System.DateTime. Path:
$.records[0].CreatedDate
有什么方法可以在反序列化之前格式化 JSON 的日期部分
Newtonsoft JSON 库可以正确反序列化字符串而不会引发异常:
using Newtonsoft.Json;
var response = JsonConvert.DeserializeObject<SFHistoryResponse>(stringResponse);
在您的情况下,您的 类 需要:
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; }
}
并且当您尝试反序列化 json
SFHistoryResponse l = JsonConvert.DeserializeObject<SFHistoryResponse>(jsonString);
自我测试
tbResult.Text = "l.records[0].CreatedDate.ToString() - " + l.records[0].CreatedDate.ToString();
具有 json 个包含日期字段的字符串
{
"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"
}
]
}
我正在尝试进行正常的反序列化,其中 CreatedDate 数据类型是 DateTime。
JsonSerializer.Deserialize<SFHistoryResponse>(stringResponse);
我得到
The JSON value could not be converted to System.DateTime. Path: $.records[0].CreatedDate
有什么方法可以在反序列化之前格式化 JSON 的日期部分
Newtonsoft JSON 库可以正确反序列化字符串而不会引发异常:
using Newtonsoft.Json;
var response = JsonConvert.DeserializeObject<SFHistoryResponse>(stringResponse);
在您的情况下,您的 类 需要:
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; }
}
并且当您尝试反序列化 json
SFHistoryResponse l = JsonConvert.DeserializeObject<SFHistoryResponse>(jsonString);
自我测试
tbResult.Text = "l.records[0].CreatedDate.ToString() - " + l.records[0].CreatedDate.ToString();