【发布时间】:2015-03-27 18:24:55
【问题描述】:
我是 spring rest 的新手,在将 JSON 对象从 jquery 映射到控制器时遇到问题。我的 jquery JSON 对象缺少一些字段,这些字段存在于控制器上的 java 对象中。我是否必须创建新类来映射此类对象,或者有什么方法可以在不创建新类的情况下映射这些对象?
这里是代码
控制器:
@RequestMapping(value = "/createTest", method = RequestMethod.POST,consumes="application/json")
@ResponseBody
public String createTest(@RequestBody TestJsonDTO testJson)
throws JsonProcessingException, IOException {
//....
TestJsonDTO:
public class TestJsonDTO {
private TestSet testSet;
private List<MainQuestion> questionsInTest;
//gettters and setters
测试集:
public class TestSet implements Serializable {
public TestSet() {
}
@Id
@GeneratedValue
private int id;
private String name;
private int fullmark;
private int passmark;
String duration;
Date createDate = new Date();
Date testDate;
boolean isNegativeMarking;
boolean negativeMarkingValue;
主要问题:
public class MainQuestion implements Serializable {
private static final long serialVersionUID = 1L;
public MainQuestion() {
}
@Id
@GeneratedValue
private int id;
private String name;
还有我的 jquery post 方法
function createTest() {
$.ajax({
type : 'POST',
url : "http://localhost:8085/annotationBased/admin/createTest",
dataType : "json",
contentType : "application/json",
data : testToJSON(),
success : function() {
alert("success")
},
error : function(msg) {
alert("error while saving test");
}
});
}
function testToJSON() {
listOfQuestionForTest = questionToAdd;//array of ids of questions
return JSON.stringify({
"testSet.name" : $('#testname').val(),
"testSet.fullmark" : parseInt($('#fullmark').val()),
"testSet.passmark" : parseInt($('#passmark').val()),
"questionsInTest" : listOfQuestionForTest
// "testDate":$('#testDate').value()
})
}
在JSON.stringify 中,我不会发送TestJsonDto 中的所有字段。我怎样才能映射这个?
【问题讨论】:
-
谢谢@Meno 但这并不能解决我的问题,因为我只想通过 TestJsonDto 将 TestSet 和 MainQuestion 的几个字段发送到控制器。我的问题是我是否必须创建一个新课程才能做到这一点?
标签: java javascript jquery json spring