【问题标题】:Jackson Object Mapper in Spring not working春季的杰克逊对象映射器不起作用
【发布时间】:2015-12-23 03:05:14
【问题描述】:

我有 Spring MVC 应用程序,它接收来自 Javascript 前端的 JSON POST。 使用 Jackson 2,自定义对象映射器仅将 ACCEPT_SINGLE_VALUE_AS_ARRAY 设置为 true。 下面是我的代码 sn-p。

启用 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: {"dstState":"NV" ,"dstCities":"Las Vegas"}

收到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

请指出我在这里遗漏的任何内容

【问题讨论】:

  • 显示将发送的其余部分
  • JSON 对象发布: mydata: {"dstState":"NV" ,"dstCities":"Las Vegas"} $.ajax({ url: ".../home", type: " POST",数据:JSON.stringify(("#logdForm").serializeArray()),contentType:“application/json”,dataType:'json',....
  • 这对您有帮助吗? stackoverflow.com/questions/14588727/…
  • @JamesJithin Pointed 问题是针对 javax.ws.rs 和 Codehaus jackson 的,我没有使用 Provider 注释 :(

标签: json spring spring-mvc jackson


【解决方案1】:

你输入的json数据格式不正确。

ShipmentJson 表示:

  • Shipment 是 Json 对象
  • String dstState 也是 Json 对象
  • List&lt;String&gt; dstCities 是 Json 数组

Shipment 类的正确 Json 数据格式类似于

 [{"dstState":"NV" , "dstCities": ["Las Vegas"]}]

[{"dstState":"NV" , "dstCities": ["Las Vegas", "Las Not Vegas"]}]

【讨论】:

    猜你喜欢
    • 2011-10-22
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 2015-10-19
    • 1970-01-01
    • 2017-12-04
    • 2014-10-10
    相关资源
    最近更新 更多