首页 > 解决方案 > 如何访问字符串 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”的值?

标签: javaspringrestjackson

解决方案


您将需要一个中间 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;
    }
}

推荐阅读