ASP.NET Core Web API中JSON反序列化对象错误排查求助
React Native调用ASP.NET Core Web API时的JSON反序列化错误
错误信息
{"errors": {"Listmodel": ["Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[sistap_api.Models.AmbarHareketRequestModel]' 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) 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 'Listmodel', line 1, position 13."]}, "status": 400, "title": "One or more validation errors occurred.", "traceId": "00-3cd8a186e7bcd84f93c8c18bef8ca908-f4fbb2109d75914d-00", "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1"}
前端React Native请求代码
const ambarHareketOnay = async () => { const convertedData = route.params.data.map(item => ({ KullaniciId: parseInt(route.params.userId), RuloSiparisDetayId: parseInt(item.RuloSiparisDetayID), EskiLokasyonAmbar: parseInt(item.AmbarID), EskiLokasyonKoridor: parseInt(item.AmbarID), YeniLokasyonAmbar: parseInt(route.params.ambarId), YeniLokasyonKoridor: parseInt(secilenKoridorId), })); console.log("data: ",convertedData); try { fetch(global.apiDomain + 'api/ambarHareket', { method: 'post', headers: { Accept: 'application/json', 'Content-type': 'application/json', }, body: JSON.stringify({ Listmodel: convertedData }), })
前端转换后的数据
data: [{"EskiLokasyonAmbar": 1, "EskiLokasyonKoridor": 1, "KullaniciId": 1, "RuloSiparisDetayId": 50328, "YeniLokasyonAmbar": 1, "YeniLokasyonKoridor": 1048}, {"EskiLokasyonAmbar": 1, "EskiLokasyonKoridor": 1, "KullaniciId": 1, "RuloSiparisDetayId": 50330, "YeniLokasyonAmbar": 1, "YeniLokasyonKoridor": 1048}]
后端ASP.NET Core Web API代码
接口控制器
[HttpPost] public IActionResult ambarHareketOnay ([FromBody] List<AmbarHareketRequestModel> Listmodel)
请求模型
public class AmbarHareketRequestModel { public int KullaniciId { get; set; } public int RuloSiparisDetayId { get; set; } public int EskiLokasyonAmbar { get; set; } public int EskiLokasyonKoridor { get; set; } public int YeniLokasyonAmbar { get; set; } public int YeniLokasyonKoridor { get; set; } }
错误原因
后端接口期望接收的是JSON数组(对应List<AmbarHareketRequestModel>类型),但前端发送的是一个包含Listmodel字段的JSON对象,数据结构不匹配,导致反序列化失败。
解决方案
方案一:修改前端请求,直接发送数组
将请求body改为直接序列化convertedData数组,无需包装在Listmodel对象中:
body: JSON.stringify(convertedData),
方案二:修改后端接收模型,使用包装类
如果需要保留前端现有请求结构,可以创建一个包装类来接收数据:
public class AmbarHareketRequestWrapper { public List<AmbarHareketRequestModel> Listmodel { get; set; } }
然后更新接口参数:
[HttpPost] public IActionResult ambarHareketOnay ([FromBody] AmbarHareketRequestWrapper request)
后续在接口逻辑中通过request.Listmodel获取数据即可。
内容的提问来源于stack exchange,提问作者İbrahim Ethem Bildirici
相关产品推荐
相关产品推荐

