I have SpringBoot application with that dependencies:
org.springframework.boot
SpringBoot by default comes with this functionality. You just have to use @RequestBody
annotation in parameter declaration of your controller method but in contrast to @so-random-dude's answer you don't have to annotate fields with @JsonProperty
, that is not required.
You just have to provide getters and setters for your custom XML object class. I am posting an example below for simplicity.
Example:
Controller method declaration:-
@PostMapping("/create")
public ResponseEntity<ApplicationResponse> createNewPost(@RequestBody CreatePostRequestDto createPostRequest){
//do stuff
return response;
}
Your custom XML object class:-
public class CreatePostRequestDto {
String postPath;
String postTitle;
public String getPostPath() {
return postPath;
}
public void setPostPath(String postPath) {
this.postPath = postPath;
}
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
}
Spring boot comes with Jackson out-of-the-box which will take care of un-marshaling JSON request body to Java objects
You can use @RequestBody Spring MVC annotation to deserialize/un-marshall JSON string to Java object... For example.
@RestController
public class CustomerController {
//@Autowired CustomerService customerService;
@RequestMapping(path="/customers", method= RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public Customer postCustomer(@RequestBody Customer customer){
//return customerService.createCustomer(customer);
}
}
Annotate your entities member elements with @JsonProperty with corresponding json field names.
public class Customer {
@JsonProperty("customer_id")
private long customerId;
@JsonProperty("first_name")
private String firstName;
@JsonProperty("last_name")
private String lastName;
@JsonProperty("town")
private String town;
}