【问题标题】:How to fix deserialization error when posting an array of objects发布对象数组时如何修复反序列化错误
【发布时间】:2019-09-14 11:02:45
【问题描述】:

"Message": "请求无效。", “模型状态”:{ “通知”:[

"无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'iBasement.Models.Notification',因为该类型需要 JSON 对象(例如 {\"name\":\"value\" }) 以正确反序列化。\r\n要修复此错误,请将 JSON 更改为 JSON 对象(例如 {\"name\":\"value\"})或将反序列化的类型更改为数组或实现的类型一个集合接口(例如 ICollection、IList),例如可以从 JSON 数组反序列化的 List。也可以将 JsonArrayAttribute 添加到该类型以强制它从 JSON 数组反序列化。\r\nPath '',第 1 行,第 1 位。”

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

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


}

【问题讨论】:

  • 您是否有机会实际发送{"notification": [....]} 而不是实际的[..]
  • @OrelEraki 不,这正是我的 PostMan 消息中当前发送正文的方式
  • 介意向我们展示正在发送的原始请求的图片吗? (正文和标题)
  • iBasement.Models.Notification 中的结构是什么。
  • @OrelEraki 添加信息

标签: c# json api


【解决方案1】:

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

  1. Host 标头重复,应将其删除。
  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 直到发现不匹配邮递员

【讨论】:

  • 感谢您在这里与我在一起。那是主要问题。如果没有适当的 Route 装饰,它会尝试执行标准 Post。我仍在试图弄清楚如何将数组从正文中获取到列表中。我可以在另一条评论中问你或更新上面的问题,还是我应该完全打开一个新线程?
  • 这很令人困惑,因为你问X,我回答Y,所以如果你在X上打开一个新问题,它可能被视为重复。在这里继续解决异常会更好。但!我在本地使用了您的确切场景并且效果很好,因此我建议您在此之前尝试 Fiddler 或 curl。 (是的,我知道 PostMan 非常适合)
猜你喜欢
  • 2023-01-15
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-06
相关资源
最近更新 更多