springmvc 以 form-data 方式请求时,嵌套参数如何绑定?

// Controller 代码

@RequestMapping(value = "/test", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public String test(User user) {
    return user.toString();
}
// 用于接收参数的类

@NoArgsConstructor
@Data
public class User {
    private String username;
    private String password;
    private Detail detail;

    @Data
    public class Detail {
        private String gender;
        private String location;

        public Detail() {
        }
    }
}
// 前端请求代码

$.post("http://localhost:8083/rrt/test", {
    "username": "aaaa",
    "password": "bbbb",
    "detail": {
        "gender": "male",
        "location": "Beijing"
    }
})

当这么发送数据时,后端就会报错:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.beans.NullValueInNestedPathException: Invalid property 'detail' of bean class [com.example.demo.param.User]: Could not instantiate property type [com.example.demo.param.User$Detail] to auto-grow nested property path; nested exception is java.lang.NoSuchMethodException: com.example.demo.param.User$Detail.<init>()] with root cause

在 application/json 发送时,采用 @ResponseBody 就可以正确的绑定嵌套参数;那么在 form-data 的请求方式中,该如何做呢?

阅读 4.4k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题