在我的 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
一切正常,我的控制器方法得到了正确的类型。但是当我在我的控制器方法中发送数组时,我得到的是List
而不是数组。
是否有可能(如果是这样 - 如何(配置 Spring + Jackson 以获得数组(仅在这种特殊情况下(而不是List
用于request.getValue()
的杰克逊配置USE_JAVA_ARRAY_FOR_JSON_ARRAY
,你可以在这里阅读它。它将为您要反序列化的 POJO 中的Object
字段创建一个Object[]
而不是List
。使用此配置的示例:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY);
此处的 Spring 引导文档描述了如何配置 Spring 引导使用的ObjectMapper
。基本上,您必须在相关属性文件中设置此环境属性:
spring.jackson.deserialization.use_java_array_for_json_array=true