@RequestBody is always empty in Spring

JSONObject is always empty for the method below.

@RequestMapping(value = "/package/{id}", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @ResponseBody public SPackage updatePackage(@PathVariable String id, @RequestBody JSONObject sPackage) { } 

and my ajax is like that. I get the object as a blank card on the server side

  var jsonObject= {"customerName":$('#customerName').val()} var jsonData = JSON.stringify(jsonObject); $.ajax({ type: "PUT", url: "http://localhost:8081/someproj/package/" + $('#id').val(), dataType: "json", data: jsonData, async: false, contentType: "application/json; charset=utf-8", beforeSend : function() { openModal(); }, success: function(data) { closeModal(); $('#success').show(); console.log(data); } }); 
+1
source share
2 answers

I think spring doesn't know to convert json to JSONObject , it would be best to accept a POJO object that has a similar structure to your json ,

 @RequestMapping(value = "/package/{id}", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @ResponseBody public SPackage updatePackage(@PathVariable String id, @RequestBody YourJsonPOJO sPackage) { } 
+1
source

Are you sure that there are no exceptions in your Spring code. When converting from JSON to a custom object in Spring, you need to specify a custom class that has the same fields and format as the incoming JSON. Otherwise, Spring doesn't know who to convert the HTTP POST data into a Java object.

In your case, you can define a POJO as follows:

 public class MyRequestObj { private String customerName; // add more fields for any other keys from JSON } 

And put this in your controller class:

 @RequestMapping(value = "/package/{id}", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @ResponseBody public SPackage updatePackage(@PathVariable String id, @RequestBody MyRequestObj myRequestObj) { String customerName = myRequestObj.getCustomerName(); } 

Of course, if you only want to pass the client name as String to your controller, you can also pass it as a query string (append? CustomerName = someCustomer), and you can get it in Spring as:

 @RequestMapping(value = "/package/{id}", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @ResponseBody public SPackage updatePackage(@PathVariable String id, @RequestParam("customerName") String customerName) { } 
0
source

Source: https://habr.com/ru/post/1237394/


All Articles