【问题标题】:Cannot deserialize the current JSON array after API callAPI 调用后无法反序列化当前 JSON 数组
【发布时间】:2021-04-16 02:17:30
【问题描述】:

我有一个 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",
            "Col2": "Value",
            "Col3": "Value",
            "Col5": "Value"
         }
     ],
     [
        {
            "Col1": "Value",
            "Col2": "Value",
            "Col3": "Value",
            "Col4": [
                {
                    "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 没有太多经验,我正在尝试通过做这个项目来学习,但是这个问题是一个很大的障碍,我有点迷茫。

【问题讨论】:

  • 您能否添加您用于反序列化的类以及 api 响应?
  • @ManpritSinghSahota 你好,我添加了 api 响应,我用来反序列化的是这个 IEnumerable
  • 有时候你在json里的Col4是一个列表,有时候是一个字符串。Col4不可能是这样的。
  • @YiyiYou 对不起,我的错,Col4 一直是一个列表,有时是 API 返回的,有时不是上面的例子

标签: c# json asp.net-mvc asp.net-core


【解决方案1】:

你可以这样做:

型号:

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>";

【讨论】:

  • 这样做我得到“无法将 System.Generics.List 隐式转换为 System.Generics.IEnumerable
  • 我这样做是为了避免错误返回 (IEnumerable)JsonConvert.DeserializeObject>>(jsonString);但现在我收到了这个错误: InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List1[System.Collections.Generic.List1[ProjectName.Models.Cols]]' to type 'System.Collections.Generic.IEnumerable`1 [ProjectName.Models.Cols]'
  • 我已经更新了我的答案,你需要返回Task&lt;List&lt;List&lt;Cols&gt;&gt;&gt;
【解决方案2】:

您可以使用下面的类来反序列化您的 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-12
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多