如何在Spring Boot中读取未映射到@RequestBody模型对象的其他JSON属性

问题描述 投票:0回答:1

我有一个看起来像这样的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中有什么方法可以在请求正文中获得这些附加属性?

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

java spring-boot spring-restcontroller
1个回答
2
投票
User扩展Map<String, String> DTO并创建一个以@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()获得所有其他内容。 
© www.soinside.com 2019 - 2024. All rights reserved.