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

我正在尝试通过AJAX调用将POJO数组从客户端发送到Spring MVC RestController,每个POJO包含其他POJO列表。

我有以下POJO,即Commit:

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]

我究竟做错了什么?

回答:

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

$.ajax({

url: 'akuiteoMap',

method: 'POST',

dataType: 'json',

contentType: 'application/json',,

data : JSON.stringify(commits),

// ----^^^^^^^^^^^^^^^^^^^^^^^----

success: function(data){

console.log(data);

}

})

以上是 如何使用jQuery将包含对象数组的对象数组传递给Spring MVC控制器? 的全部内容, 来源链接: utcz.com/qa/401609.html

回到顶部