问题描述
我有一个 NET Core MVC Web 应用程序,我在其中调用 API 以在我的 UI 中显示结果。我正在使用 ajax 调用调用 API,但在调用 API 后,我收到以下错误消息:
处理请求时发生未处理的异常。 JsonSerializationException:无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型“ProjectName.Models.ControllerName”,因为该类型需要 JSON 对象(例如 {"name":"value"})才能正确反序列化。
来自 API 的 JSON 结果:
[
[
{
"Col1": "Value","Col2": "Value","Col3": "Value","Col4": [
{
"Value": [
{}
]
},{
"Value": [
{}
]
}
],"Col5": "Value"
}
],[
{
"Col1": "Value","Col5": "Value"
}
],{
"Value": [
{}
]
}
],"Col5": "Value"
}
]
]
我的控制器
[HttpGet,ActionName("GetData")]
public async Task<IActionResult> GetReport()
{
return this.Json(await _cuRepo.GetReportAsync("https://apiurlforcall/report"));
}
存储库
public async Task<IEnumerable<T>> GetReportAsync(string url)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Token","apiToken");
HttpResponseMessage response = await client.GetAsync(url);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
//jsonString is populated with the above JSON result
var jsonString = await response.Content.ReadAsstringAsync();
return JsonConvert.DeserializeObject<IEnumerable<T>>(jsonString);
}
else
return null;
}
}
AjaxCall(我正在尝试做的)
$.ajax({
url: "Controller/GetData",data: {},method: "GET",success: function (data) {
var json = data;
var html = "";
for (var x = 0; x < json.length; x++) {
html += "<tr><td>" + json[x].Col1+ "</td><td>" + json[x].Col2+ "</td></tr>";
}
$('#MyTable').html("");
$('#MyTable').html(html);
console.log(json);
}
});
老实说,我对 net core 没有太多经验,我正在尝试通过做这个项目来学习,但这个问题是一个很大的障碍,我有点迷失了。
解决方法
你可以这样做:
型号:
public class Cols
{
public string Col1 { get; set; }
public string Col2 { get; set; }
public string Col3 { get; set; }
public List<Col4> Col4 { get; set; }
public string Col5 { get; set; }
}
public class Col4
{
public List<Col> Value { get; set; }
}
public class Col
{
}
改变
return JsonConvert.DeserializeObject<IEnumerable<T>>(jsonString);
到
return JsonConvert.DeserializeObject<List<List<Cols>>>(jsonString);
更新:
1.改变
public async Task<IEnumerable<T>> GetReportAsync(string url)
到
public async Task<List<List<Cols>>> GetReportAsync(string url)
2.改变
var json = data;
到
var json = data[0];
3.改变
html += "<tr><td>" + json[x].Col1+ "</td><td>" + json[x].Col2+ "</td></tr>";
到
html += "<tr><td>" + json[x].col1+ "</td><td>" + json[x].col2+ "</td></tr>";
,
您可以使用下面的类来反序列化您的 json:
public class DataObject
{
public ColDetails[][] MyData { get; set; }
}
public class ColDetails
{
public string Col1 { get; set; }
public string Col2 { get; set; }
public string Col3 { get; set; }
public Col4[] Col4 { get; set; }
public string Col5 { get; set; }
}
public class Col4
{
public Value[] Value { get; set; }
}
public class Value
{
}
然后,在转换为您的类后返回您想要的对象。
使用以下代码反序列化:
JsonConvert.DeserializeObject<DataObject>(jsonString);