web api中接收 复杂类型数组参数(对象数组参数)

今天在工作中遇到一个问题,一个接口需要前端传递一个对象数组参数,但出现后台无法反序列对象的错误提示。

提示信息类似:

"Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type ‘System.Collections.Generic.IEnumerable`1[EZAPP.Models.ViewModel.IdAndScoreVM]‘ because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. ↵To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. ↵Path ‘vMs‘, line 1, position 7."

当观察传递参数的json结构时发现,

 web api中接收 复杂类型数组参数(对象数组参数)

 还是标准的key-value形式的json,JSON 字符串。但观察后端参数,

web api中接收 复杂类型数组参数(对象数组参数)

 该需要的参数是数组 List等 集合参数。自然不会识别成key-value形式的。

  小笨的解决方案是:构造一个简单的对象,类似:

     web api中接收 复杂类型数组参数(对象数组参数)

因为现在参数同是一个类 一个对象,前端依然不变在Request Body中HTTP POST传递参数,如:

前端提交参数:

    web api中接收 复杂类型数组参数(对象数组参数)

 后端接收并解析成需要的数组/List 对象:

 web api中接收 复杂类型数组参数(对象数组参数)

 调试一下给你看:

web api中接收 复杂类型数组参数(对象数组参数)

 web api中接收 复杂类型数组参数(对象数组参数)

 可以看到,已经反序列化为需要的数据类型

完~

相关推荐