I have Spring MVC app which receives JSON POSTed from Javascript frontend. Using Jackson 2, custom object mapper only to set ACCEPT_SINGLE_VALUE_AS_ARRAY as true. Below is my code snippet.
Enable MVC Java config:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(0, jackson2Converter());
}
@Primary
@Bean
public MappingJackson2HttpMessageConverter jackson2Converter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(objectMapper());
return converter;
}
@Primary
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
return objectMapper;
}
}
Controller.java:
@RequestMapping(value = "home", method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public String submitForm(@RequestBody final Shipment shipment) {
...
}
POJO:
class Shipment implements Serializable {
private String dstState;
private List<String> dstCities;
// getters, setters and default constructor
}
Ajax POST call:
$.ajax({ url: ".../home", type: "POST", data: JSON.stringify(("#shipForm").serializeArray()), contentType: "application/json", dataType: 'json', ....
JSON object posted: mydata: {"dstState":"NV" ,"dstCities":"Las Vegas"}
Upon receiving POST, there is error:
Could not read JSON: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token
at [Source: java.io.PushbackInputStream@44733b90; line: 1, column: 90] (through reference chain: com.*.Shipment["dstCities"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token
Please point to anything I am missing here