jeudi 26 mars 2015

How to pass JSON complex objects without filling all attributes Spring MVC

My problem is the following:


I have a Test class with these attributes:



public class Test {
private Long id;
private String value1;
private String value2;
private int value3;
private AnotherClass idAnotherClass;

// getters and setters
}


In the AnotherClass I have these attributes:



public class AnotherClass{
private Long id;
private String value4;
private int value5;

// getters and setters
}


I can submit a AJAX post request passing value1, value2 and value3 to my Spring MVC server by using this RequestMapping:



@RequestMapping(value = RestUriConstants.SUBMETER, method = RequestMethod.POST)
public @ResponseBody JsonResponse submeter(@RequestBody final Test test) {
....
}


However, in my client side, I have to add the value for AnotherClass attribute in Test class and I only have the primary key Id of AnotherClass.


So I'm building the AJAX like this:



var test = new Object();
test.value1 = "value1";
test.value2 = "value2";
test.value3 = 3;
test.idAnotherClass = id; // integer 3 for example

$.ajax({
url : getContextPath() + '/test/submeter',
dataType : 'json',
contentType : 'application/json',
type : 'POST',
data : JSON.stringify(test)
});


And obvious I get a Bad Request since I didn't add all the attributes of AnotherClass in the JSON object.


So, my question is: Is there a good way of pass only the id of AnotherClass instead of having to pass every single attribute of it?


My idea is to get this id in the server side to then get all the attributes and not having to have everything on client side.


Aucun commentaire:

Enregistrer un commentaire