ASP.NET C# 在读取 DataTable 时出现意外的 JSON 标记

ASP.NET C# Unexpected JSON token when reading DataTable

我在 ASP.NET 工作,在尝试将 JSON 字符串序列化到 DataTable 时出现此错误:

Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject

我读过其他有同样错误的帖子,似乎错误通常发生在 JSON 对象无效时。但是,我已经在 J​​sonLint 中验证了我的 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
    }

}

这里是上面方法返回的 JSON StudioPaymentAccess.GetStudioPaymentSchedule(customerId)

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

另一种选择是直接绑定到 return 模型,假设 DataTable 不是必需的。例如,参见 Binding an ASP.NET GridView Control to a string array.

的答案

您是否正在尝试将 RecurringPaymentResponse 对象反序列化为 System.Data.DataTable? 如果您尝试将 RecurringPaymentResponse 对象反序列化为 System.Data.DataTable,它肯定会失败。由于两个 class 的属性不相同。

您应该直接更新 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://i.stack.imgur.com/4tcns.png