将POJO转换为JSON的问题

时间:2019-04-10 16:09:10

标签: java spring spring-mvc

我正在开发REST API,并且我使用Spring-mvc(否spring-boot

@RestController
@RequestMapping(value = "/api")
public class restController {

    ...

    @GetMapping(value = "/sectors")
    public List<SimpleDto> getSectors() {
        return dao.getSectors();
    }

我的dto:

public class SimpleDto {

    public Integer value;
    public String label;

    // with getter and setter and defalut and custom constructors

WebConfig.java

@Configuration
@EnableWebMvc
@ComponentScan({"controllers"})
public class WebConfig {}

并转换为json,我将其添加到 pom.xml 中:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

一切正常,但是当我用Git克隆此项目以在家中对其进行唤醒时,我发出ajax请求时收到此错误:

Resolved [org.springframework.http.converter.HttpMessageNotWritableException: 
No converter found for return value of type: class java.util.ArrayList]

我通过添加此内容进行了修复

pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.8</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.8</version>
</dependency>

WebConfig.java

@Configuration
@EnableWebMvc
@ComponentScan({"controllers"})
public class WebConfig extends WebMvcConfigurationSupport {

      @Bean
      public ObjectMapper getObjectMapper()  {
        return new ObjectMapper();
      }

      @Bean
      public MappingJackson2HttpMessageConverter messageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(getObjectMapper());
        return converter;
      }

      @Override
      public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(messageConverter());
        addDefaultHttpMessageConverters(converters);
      }
}

为什么仅在一台计算机上发生此错误?

0 个答案:

没有答案