如何使用jQuery将包含对象数组的对象数组传递给Spring MVC控制器?

时间:2017-06-26 09:10:06

标签: java jquery json spring spring-mvc

我试图通过AJAX调用向客户端发送一个POJO数组,每个POJO包含一个其他POJO列表到一个Spring MVC RestController。

我有以下POJO即提交:

public class Commit {

private long revision;
private Date date;
private String author;
private String comment;
private String akuiteo;

private List<ChangedPath> changedPathList = new ArrayList<ChangedPath>();

它包含已更改路径的列表:

public class ChangedPath extends PatchFile {

private char type;
private String copyPath;

我有以下Spring控制器:

@RestController
public class AkuiteoMapController {

static Logger log = Logger.getLogger(PatchDemoApplication.class.getName());

public AkuiteoMapController() {
    // TODO Auto-generated constructor stub
}

@RequestMapping(value="/akuiteoMap")
@ResponseBody
public AkuiteoMap getAllCommits(@RequestBody Commit[] commits) throws IOException{
    log.info("inside akuiteoMap");
    AkuiteoMap akuiteoMap=new AkuiteoMap();
    akuiteoMap= UserService.getAkuiteoMap(commits);
    log.info("akuiteo map: "+akuiteoMap);
    return akuiteoMap;
}

}

在客户端,我尝试执行以下ajax调用:

$.ajax({
        url: 'akuiteoMap',
        method: 'POST',
        dataType: 'json',
        contentType: 'application/json',// charset=utf-8',
        data:{
            commits:JSON.stringify(commits),
            //commits:commits
        },
        success: function(data){
            console.log(data);
        }
    })

我收到以下错误:

2017-06-26 10:58:40.764  WARN 4788 --- [nio-8080-exec-8] 
.w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: 
org.springframework.http.converter.HttpMessageNotReadableException: 
JSON parse error: Unrecognized token 'commits': was expecting ('true', 
'false' or 'null'); nested exception is 
com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'commits': 
was expecting ('true', 'false' or 'null')
at [Source: java.io.PushbackInputStream@e57cb2a; line: 1, column: 9]

我做错了什么?

1 个答案:

答案 0 :(得分:3)

将JSON字符串作为接受控制器方法的数据传递。

$.ajax({
    url: 'akuiteoMap',
    method: 'POST',
    dataType: 'json',
    contentType: 'application/json',,
    data : JSON.stringify(commits),
    // ----^^^^^^^^^^^^^^^^^^^^^^^----
    success: function(data){
        console.log(data);
    }
})