[英]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 参数。 但是我不想使用这些类,因为我会丢失可以在“用户”模型对象中使用的 javax.validation。
使用Map<String, String>
扩展您的User
DTO 并创建一个用@JsonAnySetter
注释的 setter。 对于所有未知属性,将调用此方法。
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()
获取其他所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.