Issue
The API below accept a json string from client, and the map it into a Email object. How can I get request body (email
) as a raw String? (I want both raw-string and typed version of email
parameter)
PS: This question is NOT a duplicate of: How to access plain json body in Spring rest controller?
@PostMapping(value = "/mailsender")
public ResponseEntity<Void> sendMail(@RequestBody Email email) {
//...
return new ResponseEntity<>(HttpStatus.OK);
}
Solution
You can do it in more than one way, listing two
1. **Taking string as the paramater**,
@PostMapping(value = "/mailsender")
public ResponseEntity<Void> sendMail(@RequestBody String email) {
//... the email is the string can be converted to Json using new JSONObject(email) or using jackson.
return new ResponseEntity<>(HttpStatus.OK);
}
2. **Using Jackson**
@PostMapping(value = "/mailsender")
public ResponseEntity<Void> sendMail(@RequestBody Email email) {
//...
ObjectMapper mapper = new ObjectMapper();
String email = mapper.writeValueAsString(email); //this is in string now
return new ResponseEntity<>(HttpStatus.OK);
}
Answered By - Ankush Sharma