gpt4 book ai didi

java - 如何在 Spring REST Controller 中获取原始 JSON 主体?

转载 作者:行者123 更新时间:2023-12-03 23:04:22 24 4
gpt4 key购买 nike

下面的 API 接受来自客户端的 json 字符串,并将其映射到 Email 对象中。如何将请求正文( email )作为原始字符串获取? (我想要 email 参数的原始字符串和类型版本)
PS:这个问题不是重复的: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);
}

最佳答案

您可以通过多种方式完成,列出两种

 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);
}

关于java - 如何在 Spring REST Controller 中获取原始 JSON 主体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63554378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com