I have a request like that:
let jsonData= {};
jsonData["className"]= className;
jsonData["models"]= arr;
let endPoint= "/classses?classAndModel=" + encodeURIComponent(JSON.stringfy(jsonData));
return $.ajax({
url: host + endPoint,
data: data,
cache: false,
contentType: false,
processData: false,
method: "POST"
});
I want to convert that json to java object.I tried this one
My rest service is:
@PostMapping(value=/classes",consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Void> addClassAndModelMapping(ClassAndModels classAndModels){
}
public class ClassAndModels {
ClassAndModelResult classAndModel;
...getter and setter...
}
public ClassAndModelResult {
String className;
List<String> models;
...getter and setters...
}
I get 400 error.If I change that line ClassAndModelResult classAndModel to String classAndResult.I get response but I want Object type.Do you have any idea?
2 Answers 2
The first part of code shows that you are sending data as a query string.
Take a look at https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html
But considering the @PostMapping, you should send that data in the request body and do something like this on the server side.
@PostMapping("/classes")
public ResponseEntity<Void> addClassAndModelMapping(@RequestBody ClassAndModels classAndModels){
//
}
As Phils says, you can add a GetMapping on your controller to see how your ClassAndModels its being serialized
Source: https://spring.io/guides/tutorials/bookmarks/
P.S. Sorry about my english, I'm not a native speaker.
4 Comments
dataType: 'json', contentType: 'application/json', and also set data: jsonDataPlease try to add @RequestParam annotation or better use classAndModel value as RequestBody similar to the below.And also correct the spelling mistake in the javascript url.
@PostMapping(value = "/classes")
public ResponseEntity<Void> addClassAndModelMapping(@RequestBody ClassAndModels modal) {
}
ClassAndModelsand serialising it to JSON to see how it compares to the JSON you are passing in?@PostMappingannotations. Looks like you are running a Spring (Boot) application, is this correct?