问题描述
我正在ASP.NET中工作,尝试将JSON字符串序列化到DataTable时遇到此错误:
读取DataTable时出现意外的JSON令牌。预期的StartArray,得到了 StartObject
我已经阅读了具有相同错误的其他帖子,并且当JSON对象无效时,似乎通常会发生该错误。但是,我已经在JsonLint中验证了JSON,这很好。我不是在构造JSON,而是从Paysimple API接收它。我在软件的其他部分也使用了非常类似的方法,并且工作正常,所以我不知所措地解释了为什么错误出现在这里。
任何帮助将不胜感激。我没有使用JSON的丰富经验。
这是我的代码:
protected void LoadPaymentSchedule(int customerId)
{
// This method returns an object from Paysimple's API
RecurringPaymentResponse recurringPayment = StudioPaymentAccess.GetStudioPaymentSchedule(customerId);
// Convert the Json response to DataTable
string a = JsonConvert.SerializeObject(recurringPayment);
DataTable tblSchedules = JsonConvert.DeserializeObject<DataTable>(a);//**error occurs here
// Bind to gridview
if (tblSchedules.Rows.Count > 0)
{
grdPaymentSchedules.DataSource = tblSchedules;
grdPaymentSchedules.DataBind();
}
else
{
//No schedules found
}
}
这是 StudioPaymentAccess.GetStudioPaymentSchedule(customerId)
上面的方法返回的JSON。{
"CustomerId": 1149814,"CustomerFirstName": "Evan W","CustomerLastName": "Studio4","CustomerCompany": null,"NextScheduleDate": "2020-11-16T07:00:00Z","PauseUntilDate": null,"FirstPaymentDone": false,"DateOfLastPaymentMade": "2020-10-16T06:00:00Z","TotalAmountPaid": 10.0,"NumberOfPaymentsMade": 1,"EndDate": "2021-10-16T06:00:00Z","PaymentAmount": 10.0,"PaymentSubType": "Moto","AccountId": 1184647,"InvoiceNumber": null,"OrderId": null,"FirstPaymentAmount": 0.0,"FirstPaymentDate": null,"StartDate": "2020-10-16T06:00:00Z","ScheduleStatus": "Active","ExecutionFrequencyType": "SpecificDayofMonth","ExecutionFrequencyParameter": 16,"Description": " ","Id": 181512,"LastModified": "2020-10-16T07:30:43Z","CreatedOn": "2020-10-15T18:11:22Z" }
解决方法
看起来是为了反序列化DataTable
(期望的JSON should be an array)。
一种快速的解决方法是调整序列化以便写出一个数组:
string a = JsonConvert.SerializeObject(new[] { recurringPayment });
另一种选择是直接绑定到返回模型,假设不需要DataTable
。例如,请参见Binding an ASP.NET GridView Control to a string array的答案。
您是否正在尝试将RecurringPaymentResponse对象反序列化为System.Data.DataTable? 如果您尝试将RecurringPaymentResponse对象反序列化为System.Data.DataTable,则它肯定会失败。由于两个类的属性不相同。
您应该直接更新gridview行
GridViewRow row = (GridViewRow) GridView1.Rows[0]; //First row
row.Cells[0].Text = recurringPayment.CustomerId;
row.Cells[1].Text = recurringPayment.CustomerFirstName;
row.Cells[2].Text = recurringPayment.CustomerLastName;
//and so on.....
DataTable期望数组为...
{
"data":
[
{"ID":1,"Name":"Simon"},{"ID":2,"Name":"Alex"}
]
}
,
我尝试反序列化,但是没有发生错误,反序列化运行成功。 https://pythonprogramming.altervista.org/platform-game-in-detail-part-1/?doing_wp_cron=1603309265.4902870655059814453125