Jackson Mapping List of String or simple String
In addition to global configuration already mentioned, it is also possible to support this on individual properties:
public class Container {
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
// ... could also add Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED
public List<String> tags;
}
I have tried this with just jackson outside Spring and it works as expected with:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
Mind that RestTemplate
registers a MappingJacksonHttpMessageConverter
with it's own ObjectMapper
. Check this answer for how to configure this ObjectMapper
.
Since it is a List of keys it will work. if in case property has single value and not in array like below DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY will ensure deserializing single property as a array
{
"CategoriesKeys":{
"categoryKey":{
"keys":"1"
}
}
}
@JsonRootName("CategoriesKeys")
protected static class CategoriesKeys{
private CategoryKey categoryKey;
//getters and setters
}
protected static class CategoryKey{
private List<String> keys;
//getters and setters
}
TestClass:
ObjectMapper mapper=new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
Output:
{"CategoriesKeys":{"categoryKey":{"keys":["1"]}}}