I have a rest endpoint (spring-boot-1.3.0-RELEASE -> spring-core-4.2.4.RELEASE) which takes a multiple instance string parameter
@RequestMapping(value = "/test", method = RequestMethod.GET)
public ResponseEntity<Object> getTest(@RequestParam(value = "testParam", required = false) String[] testParamArray) {}
/test?testParam= => testParamArray has length 0
/test?testParam=&testParam= => testParamArray has length 2 (two empty string items)
I expected that for the first case to get a single empty sting element in the array but there are none. Any ideas on how to achieve this?
Spring's StringToArrayConverter
is responsible for this conversion. If you take a look at its convert
method:
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return null;
}
String string = (String) source;
String[] fields = StringUtils.commaDelimitedListToStringArray(string);
Object target = Array.newInstance(targetType.getElementTypeDescriptor().getType(), fields.length);
for (int i = 0; i < fields.length; i++) {
String sourceElement = fields[i];
Object targetElement = this.conversionService.convert(sourceElement.trim(), sourceType, targetType.getElementTypeDescriptor());
Array.set(target, i, targetElement);
}
return target;
}
Basically, it takes the input (empty String
in your case), split it by comma and return an array with values of the exploded String
. Result of splitting an empty String
, of course, is an empty Array
.
When you pass two parameters with the same name, the ArrayToArrayConverter
will be called, which behaves as you would expect and returns an array with two empty String
s.
If you want to disable the default String
to Array
behavior, you should register another Converter
that converts an empty String
to a single element Array
.