java.lang.IllegalArgumentException: No converter found for return value of type

后端 未结 20 2087
夕颜
夕颜 2020-11-30 00:04

With this code

@RequestMapping(value = \"/bar/foo\", method = RequestMethod.GET)
    public ResponseEntity foo() {

        Foo model;
        ...         


        
20条回答
  •  旧巷少年郎
    2020-11-30 00:56

    While using Spring Boot 2.2 I run into a similiar error message and while googling my error message

    No converter for [class java.util.ArrayList] with preset Content-Type 'null'

    this question here is on top, but all answers here did not work for me, so I think it's a good idea to add the answer I found myself:

    I had to add the following dependencies to the pom.xml:

    
      org.springframework
      spring-oxm
    
    
    
      com.thoughtworks.xstream
      xstream
      1.4.11.1
    
    

    After this I need to add the following to the WebApplication class:

    @SpringBootApplication
    public class WebApplication
     {
      // ...
    
      @Bean
      public HttpMessageConverter createXmlHttpMessageConverter()
       {
        final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
        final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
        xstreamMarshaller.setAutodetectAnnotations(true);
        xmlConverter.setMarshaller(xstreamMarshaller);
        xmlConverter.setUnmarshaller(xstreamMarshaller);
        return xmlConverter;
       }
    
    }
    
    
    

    Last but not least within my @Controller I used:

    @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType. APPLICATION_JSON_VALUE})
    @ResponseBody
    public List listXmlJson(final Model model)
     {
      return this.service.list();
     }
    

    So now I got JSON and XML return values depending on the requests Accept header.

    To make the XML output more readable (remove the complete package name from tag names) you could also add @XStreamAlias the following to your entity class:

    @Table("ExampleTypes")
    @XStreamAlias("ExampleType")
    public class ExampleTypeEntity
     {
      // ...
     }
    

    Hopefully this will help others with the same problem.

    提交回复
    热议问题