【发布时间】:2020-12-10 20:45:26
【问题描述】:
我忽略了一些可能是基本的东西。尝试反序列化 JSON 文件,但出现错误。
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[RosterAppsPayrollToADP.Models.PayPeriodData]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
我认为我的设置没问题,但显然我遗漏了一些东西而且我没有看到它。
启动一个新的 C# 控制台应用程序,该应用程序最终将调用第 3 方 API,但现在我正在尝试模拟 JSON 响应应该是什么。
JSON 文件
{
"PayPeriodData": [
{
"PayrollID": "123",
"PayRoleGroupName": "Biweekly",
"PayPeriodStart": "2020-11-07",
"PayPeriodEnd": "2020-11-20",
"IsFrozen": "true",
"FrozenOn": "2020-11-25T18:03:12",
"CreatedOn": "2020-11-25T18:03:12",
"ProcessedOn": "2020-11-25T18:03:12"
},
{
"PayrollID": "124",
"PayRoleGroupName": "Weekly",
"PayPeriodStart": "2020-11-14",
"PayPeriodEnd": "2020-11-20",
"IsFrozen": "true",
"FrozenOn": "2020-11-25T18:03:12",
"CreatedOn": "2020-11-25T18:03:12",
"ProcessedOn": "2020-11-25T18:03:12"
}
]
}
模型类
public class PayPeriodRequest
{
public List<PayPeriod> PayPeriodData { get; set; }
}
public class PayPeriod
{
public string PayrollID { get; set; }
public string PayRoleGroupName { get; set; }
public string PayPeriodStart { get; set; }
public string PayPeriodEnd { get; set; }
public string IsFrozen { get; set; }
public string FrozenOn { get; set; }
public string CreatedOn { get; set; }
public string ProcessedOn { get; set; }
}
C#代码
List<PayPeriodRequest> listPayPeriodData = _dataManager.GetPayPeriodData();
数据管理器
public List<PayPeriodRequest> GetPayPeriodData()
{
_log.LogInformation("Getting pay period data.");
List<PayPeriodRequest> listPayPeriodData = new List<PayPeriodRequest>();
try
{
string jsonData = System.IO.File.ReadAllText(@"D:\PayPeriodDataSample.json");
listPayPeriodData = JsonConvert.DeserializeObject<List<PayPeriodRequest>>(jsonData);
}
catch (Exception ex)
{
_log.LogError("Error getting pay period data. {0} | {1} | {2}", ex.Message, ex.StackTrace, ex.InnerException);
}
return listPayPeriodData;
}
【问题讨论】:
-
你有一个 json 对象,它的属性是一个数组。对象本身不是数组。您需要将其解析为对象并在其中引用 PayPeriodData。
-
根据之前的评论,您需要反序列化为
PayPeriodRequest,而不是List<PayPeriodRequest> -
知道了。谢谢!
标签: c# json asp.net-core .net-core deserialization