下面的API接受来自客户端的json字符串,并将其映射到电子邮件对象中。如何将请求正文(email
(作为原始字符串获取?(我想要原始字符串和键入的email
参数版本(
PS:这个问题不是:如何在Spring rest控制器中访问纯json主体?
@PostMapping(value = "/mailsender")
public ResponseEntity<Void> sendMail(@RequestBody Email email) {
//...
return new ResponseEntity<>(HttpStatus.OK);
}
您可以用多种方式来实现,列出两种
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);
}
Spring在后面使用Jackson,您可以使用它将其序列化为字符串。像这样:
@Autowired private ObjectMapper jacksonMapper;
@PostMapping(value = "/mailsender")
public ResponseEntity<Void> sendMail(@RequestBody Email email) {
//...
log.info("Object as String: " + jacksonMapper.writeValueAsString(email));
return new ResponseEntity<>(HttpStatus.OK);
}
我并没有完全了解这个问题,但我试着根据自己的理解来回答。好如果您想获得请求正文:
-
正如您所说,如何在Spring rest控制器中访问纯json主体?这里已经写了如何做到这一点。如果出现问题,可能是您发送了错误的json或不适合的类型,正如您在
Email
类中看到的那样。也许你的请求来自url过滤器 -
第二种方法:
private final ObjectMapper mapper = new ObjectMapper(); @PostMapping(value = "/mailsender") public ResponseEntity<Void> sendMail(HttpServletRequest req) { // read request body InputStream body = req.getInputStream(); byte[] result = ByteStreams.toByteArray(body); String text =new String(result,"UTF-8"); //convert to object Email email = mapper.readValue(body, Email .class); return new ResponseEntity<>(HttpStatus.OK); }
如果您想将对象转换为json字符串,请阅读这篇文章
您可以使用GSON库创建字符串类型的json
Gson gson = new Gson();
@PostMapping(value = "/endpoint")
public ResponseEntity<Void> actionController(@RequestBody Car car) {
//...
log.info("Object as String: " + this.gson.toJson(car));
return new ResponseEntity<>(HttpStatus.OK);
}