在我的 Spring Boot 应用程序中,我有以下 @RestController
方法:
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{decisionId}/decisions/{childDecisionId}/characteristics/{characteristicId}/values", method = RequestMethod.POST)
public ValueResponse create(@PathVariable @NotNull @DecimalMin("0") Long decisionId, @PathVariable @NotNull @DecimalMin("0") Long childDecisionId, @PathVariable @NotNull @DecimalMin("0") Long characteristicId,
@Valid @RequestBody CreateValueRequest request, Authentication authentication) {
....
request.getValue()
...
}
这是我的 CreateValueRequest
DTO:
public class CreateValueRequest implements Serializable {
private static final long serialVersionUID = -1741284079320130378L;
@NotNull
private Object value;
...
}
该值可以是例如 String
、Integer
、Double
以及相应的数组,如 String[]
, Integer[]
..等
在 String
、Integer
、Double
的情况下,一切正常,我在 Controller 方法中得到了正确的类型。但是当我在我的 Controller 方法中发送一个数组时,我得到的是 List
而不是数组。
是否有可能(如果可以 - 如何)配置 Spring + Jackson 以获得数组(仅在这种特殊情况下)而不是 request.getValue()< 的
List
/
最佳答案
执行此操作的 Jackson 配置是 USE_JAVA_ARRAY_FOR_JSON_ARRAY
,您可以阅读它 here .它将为要反序列化到的 POJO 中的 Object
字段创建一个 Object[]
而不是 List
。使用此配置的示例:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY);
Spring Boot 文档 here描述了如何配置 Spring Boot 使用的 ObjectMapper
。基本上你必须在相关的属性文件中设置这个环境属性:
spring.jackson.deserialization.use_java_array_for_json_array=true
关于java - Spring Jackson 数组而不是 List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43167846/