java - 如何访问字符串 json 有效负载并将其映射到 Spring 休息控制器中的对象?
问题描述
我正在使用 Spring Boot 休息服务构建一个休息 API。我有一个 Java 类:
class Person{
int id;
@notNull
String name;
@notNull
String password;
}
我想制作一个 API 来创建一个 Person 对象。我将收到一个带有 json 正文的 POST 请求,例如:
{
"name":"Ahmad",
"password":"myPass",
"shouldSendEmail":1
}
正如您所看到的,有一个额外的字段“shouldSendEmail”,我必须使用它来了解在创建人员对象后是否应该发送电子邮件。我正在使用以下 API:
@RequestMapping(value = "/AddPerson", method = RequestMethod.POST)
public String savePerson(
@Valid @RequestBody Person person) {
personRepository.insert(person);
// Here I want to know if I should send an email or Not
return "success";
}
当我以这种方式使用自动映射时,是否有一种方法可以访问“shouldSendEmail”的值?
解决方案
您将需要一个中间 DTO,否则您将不得不修改 person 以包含 shouldSendEmail 的字段。如果这不可能,唯一的另一种选择是使用 JsonNode 并从树中手动选择属性。
例如,
@Getter
public class PersonDTO {
private final String name;
private final String password;
private final Integer shouldSendEmail;
@JsonCreator
public PersonDTO(
@JsonProperty("name") final String name,
@JsonProperty("password") final String password,
@JsonProperty("shouldSendEmail") final Integer shouldSendEmail
) {
this.name = name;
this.password = password;
this.shouldSendEmail = shouldSendEmail;
}
}
推荐阅读
- javascript - 在 Node JS Mongoose 中创建第二个用户返回错误
- reactjs - 如何从电子应用程序启动连帽衫服务器
- mongodb - 使用 Docker 和 MongoDB 连接到其他复制 VM
- html - 如何从带有圆角的粘性表格标题中删除透明度,以便您看不到后面的单元格边框?
- python - 使用 python spacy 从字符串中删除单词而不影响单词
- javascript - javascript套接字服务器正在覆盖变量
- rust - Rust 中的字典比较
- reactjs - appbar材料ui中的下拉菜单项 - React
- python - 使用海龟图形绘制 n 角星
- android - Flutter - 在 android 模拟器中显示多个屏幕