我有Spring MVC应用程序,它接收从Javascript前端发布的JSON。 使用Jackson 2,自定义对象映射器仅将ACCEPT_SINGLE_VALUE_AS_ARRAY设置为true。 以下是我的代码段。
启用MVC Java配置:
@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调用:
$.ajax({ url: ".../home", type: "POST", data: JSON.stringify(("#shipForm").serializeArray()), contentType: "application/json", dataType: 'json', ....
发布的JSON对象:mydata:{&#34; dstState&#34;:&#34; NV&#34; ,&#34; dstCities&#34;:&#34;拉斯维加斯&#34;}
收到POST后,出现错误:
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
请指出我在这里失踪的任何事情
答案 0 :(得分:0)
您输入的json数据格式不正确。
Shipment
Json代表:
Shipment
是Json对象String dstState
也是Json对象List<String> dstCities
是Json Array 正确的Shipment
类的Json数据格式就像
[{"dstState":"NV" , "dstCities": ["Las Vegas"]}]
或
[{"dstState":"NV" , "dstCities": ["Las Vegas", "Las Not Vegas"]}]