Spring Jackson 数组代替列表

ale*_*oid 1 java spring jackson spring-restcontroller

在我的 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()
        ...
    }
Run Code Online (Sandbox Code Playgroud)

这是我的CreateValueRequest DTO:

public class CreateValueRequest implements Serializable {

    private static final long serialVersionUID = -1741284079320130378L;

    @NotNull
    private Object value;

...

}
Run Code Online (Sandbox Code Playgroud)

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

如果是String, IntegerDouble一切工作正常,并且我在控制器方法中得到了正确的类型。但是当我在控制器方法中发送数组时,我得到的List不是数组。

是否可以(如果是的话 - 如何)配置 Spring + Jackson 以获取数组(仅在这种特殊情况下)而不是Listforrequest.getValue()

Man*_*dis 5

Jackson 配置就是这样做的,您可以在这里USE_JAVA_ARRAY_FOR_JSON_ARRAY阅读它。它将为您要反序列化到的 POJO 中的字段创建一个而不是一个。使用此配置的示例:Object[]ListObject

ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY);
Run Code Online (Sandbox Code Playgroud)

这里的 Spring Boot 文档描述了如何配置ObjectMapperSpring Boot 使用的。基本上,您必须在相关属性文件中设置此环境属性:

spring.jackson.deserialization.use_java_array_for_json_array=true
Run Code Online (Sandbox Code Playgroud)