javascript - Spring 正在将 2D JSON 数组展平为 1D 字符串数组
问题描述
我正在使用 AJAX 将表单数据发布到 Spring 控制器。我将一个二维数组附加到我的表单数据中,data.push({name: "currentRoles", value: optionsArray});
并尝试接收它,Map<String, String>
但是我得到了错误Resolved [org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException: Failed to convert value of type 'java.lang.String[]'
。由于某种原因,该阵列似乎被扁平化为一维阵列。数组的形式为:{name: "currentRoles", value: Array(2)}
.
完整的 JS:
var roles = $(".selectpicker.role");
var optionsArray = [];
$.each(roles, function(index, item){
var testArray = [];
$.each($(roles[index]).find("option:selected"), function(index2, item2){
testArray.push($(item2).val());
});
optionsArray.push(testArray);"name":"currentRoles"}).val(optionsArray);
});
data.push({name: "currentRoles", value: optionsArray});
编辑:尝试更改Map<String, String>
为Map<String, Object>
,没有任何区别
我的控制器:
@PostMapping(value="/AdminEditGroup")
public ModelAndView editGroup(@RequestParam String groupName, @RequestParam (required = false) String[] currentMembers,
@RequestParam (required = false) String currentFramework, @RequestParam (required = false) RoleWrapper currentRoles,
@RequestParam String originalName, Model model){}
角色包装器:
public class RoleWrapper {
private Map<String, Object> roleWrapper = new HashMap<String, Object>();
public Map<String, Object> getRoleWrapper() {
return roleWrapper;
}
public void setRoleWrapper(Map<String, Object> roleWrapper) {
this.roleWrapper = roleWrapper;
}
}
编辑:作为 Andreas 答案的扩展,我已将控制器方法更改为以下内容:
@PostMapping(value="/AdminEditGroup", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ModelAndView editGroup(@RequestParam MultiValueMap request, Model model){
logger.info(request.toString());
}
这反过来产生输出:currentRoles=[Student, Teacher, Student, Student,Teacher,Student]
对于 JSON
{
"name": "currentRoles",
"value": [
["Student", "Teacher"],
["Student"]
]
}
信息被复制并再次展平为一维数组。我怀疑这与 Spring 如何转换表单数据有关。
解决方案
您发送的 JSON 可能如下所示:
{
"name": "currentRoles",
"value": [
["val1", "val2", "val3"],
["val4", "val5"],
["val6", "val7", "val8", "val9"]
]
}
要接收这种有效负载,您需要将方法定义为:
@PostMapping(value="/AdminEditGroup", consumes="application/json")
public ModelAndView editGroup(@RequestBody Map<String, Object> request, Model model) {
String name = (String) request.get("name");
List<List<String>> = (List) request.get("value");
// code
}
当然,除非您将data
问题代码中显示的内容包装成更复杂的内容,但是由于您没有共享该内容,因此我们无能为力。
推荐阅读
- python - 我无法通过 wordpress_xmlrpc 从 python 发布到我的 wordpress 站点我得到 ExpatError: not well-formed (invalid token): line 1, column 222
- dns - 如何获取 DNS Nameserver 的 IP 地址
- powerbi - 尝试使用 Power BI 计算梯度的问题
- jquery - 我正在尝试使图像可拖动,但是每当我调整高度和宽度时,它就会停止工作
- excel - 当至少一行满足条件时对所有行求和
- reactjs - 在 reducer 中更改状态后组件未更新
- javascript - 用于获取文本并相应更改 div 样式的 Jquery 函数
- android - 为什么 CSS 中的点单位等于 1.333 像素?
- google-cloud-platform - “gcloud auth application-default login”和“gcloud auth login”之间的区别
- python - 远程使用 Luigi 时查看任务进度(使用 ssh)