首页 > 解决方案 > 发布对象数组时如何修复反序列化错误

问题描述

"Message": "请求无效。", "ModelState": { "notification": [

“无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'iBasement.Models.Notification',因为该类型需要 JSON 对象(例如 {\"name\":\"value\"})正确反序列化。\r\n要修复此错误,请将 JSON 更改为 JSON 对象(例如 {\"name\":\"value\"})或将反序列化的类型更改为数组或实现集合接口的类型“

尝试使用这样的数组调用帖子:

POST /api/Notifications/UpdateMac HTTP/1.1
Host: localhost:56005
Content-Type: application/json
User-Agent: PostmanRuntime/7.17.1
Accept: */*
Cache-Control: no-cache
Postman-Token: 4ac88367-af2c-48e8-99a0-b89fba2ea76a,c1f78db8-e040-4675-9103-5c9c41273c24
Host: localhost:56005
Accept-Encoding: gzip, deflate
Content-Length: 507
Connection: keep-alive
cache-control: no-cache

[
    {
        "Id": 1,
        "MacAddress": "f8:f0:05:ed:1d:28",
        "Destination": "janedoe@gmail.com",
        "SendAlertTypes": "0,1,4,5,6"
    },
    {
        "Id": 6,
        "MacAddress": "f8:f0:05:ed:1d:28",
        "Destination": "johndoe@hotmail.com",
        "SendAlertTypes": "0,1,2,3,4,5,6"
    },
    {
        "Id": 99,
        "MacAddress": "f8:f0:05:ed:1d:28",
        "Destination": "4012221234@vtext.com",
        "SendAlertTypes": "0,1,2,3,4,5,6"
    }
]

[Route("~/UpdateMac")]
public async Task<HttpResponseMessage> PostNotifications([FromBody]List<Notification> notifications)
{
    //do list operations..
}

public class Notification

{
    public int Id { get; set; }
    public string MacAddress { get; set; }
    public string Destination { get; set; }
    //"0,1,2,3,6" <-- 4, 5, & 7+ would be omitted
    public string SendAlertTypes { get; set; }


}

标签: c#jsonapi

解决方案


你有几个问题,但没有一个是你得到的例外。

  1. 主机标头重复,应将其删除。
  2. 路由
    代码示例正在使用[Route("~/UpdateMac")],这意味着“忽略所有路由前缀属性”,因此,您只能调用此操作,而之前没有任何其他路径。
    不会工作:POST /api/Notifications/UpdateMac HTTP/1.1
    会工作:POST /UpdateMac HTTP/1.1

如果您仍想使用完整的/api/Notifications/UpdateMac路由,这里有几种方法

  1. 更改[Route("~/UpdateMac")][Route("api/Notifications/UpdateMac")]
  2. 装饰控制器[RoutePrefix("api/Notifications")]并将动作更改为[Route("UpdateMac")](不带波浪号)。

在这些实验中,我都没有遇到反序列化问题,这可能意味着客户端以某种方式产生不同的请求,尝试使用Fiddlercurl直到在PostMan中找到不匹配。


推荐阅读