首页 > 解决方案 > 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 如何转换表单数据有关。

标签: javascriptjavaarraysjsonspring

解决方案


您发送的 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问题代码中显示的内容包装成更复杂的内容,但是由于您没有共享该内容,因此我们无能为力。


推荐阅读