Spring 杰克逊数组而不是列表

Spring Jackson array instead of List

在我的 Spring 引导应用程序中,我有以下 @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;

...

}

该值可以是例如 StringIntegerDouble 以及相应的数组,例如 String[]Integer[].. 等等

StringIntegerDouble 的情况下,一切正常,我在控制器方法中得到了正确的类型。但是当我在我的控制器方法中发送一个数组时,我得到的是 List 而不是 array.

是否有可能(如果可以 - 如何)配置 Spring + Jackson 以获得数组(仅在这种特殊情况下)而不是 List for request.getValue()

执行此操作的 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