弹簧杰克逊数组而不是列表



在我的 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;
...
}

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

String的情况下,IntegerDouble一切正常,我的控制器方法得到了正确的类型。但是当我在我的控制器方法中发送数组时,我得到的是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

最新更新