今天在工作中遇到一個問題,一個接口需要前端傳遞一個對象數組參數,但出現后台無法反序列對象的錯誤提示。
提示信息類似:
"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結構時發現,
還是標准的key-value形式的json,JSON 字符串。但觀察后端參數,
該需要的參數是數組 List等 集合參數。自然不會識別成key-value形式的。
小笨的解決方案是:構造一個簡單的對象,類似:
因為現在參數同是一個類 一個對象,前端依然不變在Request Body中HTTP POST傳遞參數,如:
前端提交參數:
后端接收並解析成需要的數組/List 對象:
調試一下給你看:
可以看到,已經反序列化為需要的數據類型
完~