如何在 Spring 引导中读取未映射到 @RequestBody 模型对象的附加 JSON 属性

How to read additional JSON attribute(s) which is not mapped to a @RequestBody model object in Spring boot

我有一个看起来像这样的 RestController

@RequestMapping(value = "/post", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> test(@RequestBody User user) {

    System.out.println(user);
    return ResponseEntity.ok(user);
}     

以及如下所示的用户模型

class User {

    @NotBlank
    private String name;
    private String city;
    private String state;

}

我有一个要求,用户可以在输入中传递一些额外的附加属性 JSON,像这样

{
"name": "abc",
"city": "xyz",
"state": "pqr",
"zip":"765234",
"country": "india"
}

'zip' 和 'country' 是输入 JSON 中的附加属性。

有什么办法可以在Spring Boot 中获取Request Body 中的这些附加属性吗?

我知道一种方法,我可以使用 "Map" 或 "JsonNode" 或 "HttpEntity" 作为 Requestbody 参数。但是我不想使用这些 类,因为我会丢失可以在 "User" 模型对象中使用的 javax.validation。

使用 Map<String, String> 扩展您的 User DTO 并创建一个 setter 并用 @JsonAnySetter 注释。对于所有未知属性,将调用此方法。

class User {

    private final Map<String, Object> details= new HashMap<>);

    @NotBlank
    private String name;
    private String city;
    private String state;

    @JsonAnySetter
    public void addDetail(String key, Object value) {
      this.details.add(key, value);
    }

    public Map<String, Object> getDetails() { return this.details; }
}

现在您可以通过getDetails()获得其他一切。