Search code examples
javaspringjacksonspring-restcontroller

Spring Jackson array instead of List


In my Spring Boot application I have a following @RestController method:

@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()
        ...
    }

This is my CreateValueRequest DTO:

public class CreateValueRequest implements Serializable {

    private static final long serialVersionUID = -1741284079320130378L;

    @NotNull
    private Object value;

...

}

The value can be for example String, Integer, Double and the corresponding arrays like String[], Integer[].. etc

In case of String, Integer, Double everything is working fine and I'm getting a correct type in my controller method. But when I send an array in my controller method I'm getting List instead of array.

Is it possible (and if so - how ) to configure Spring + Jackson in order to get array (only in this particular case) instead of List for request.getValue()


Solution

  • The Jackson configuration that does that is USE_JAVA_ARRAY_FOR_JSON_ARRAY and you can read about it here. It will create an Object[] instead of a List for an Object field in the POJO you are deserializing into. An example using this config:

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY);
    

    The documentation for Spring Boot here describes how to configure the ObjectMapper that Spring Boot uses. Basically you have to set this environment property in the pertinent properties file:

    spring.jackson.deserialization.use_java_array_for_json_array=true