HTTP消息不可写异常错误:找不到以下类型的返回值的转换器:Spring MVC中的类java.util.HashMap

o2g1uqev  于 2022-11-14  发布在  Spring
关注(0)|答案(6)|浏览(147)

我尝试在控制器的方法中使用HashMap返回一个json,如下所示

//list all users
    @RequestMapping(value = "/user",method = RequestMethod.GET)
    public ResponseEntity<Map<String,Object>> handleRequest() throws Exception{
        List<User> users = userService.list();          
        Map<String, Object> message = new HashMap<String, Object>();

        message.put("severity", "info");
        message.put("user", users);
        message.put("summary", "Not successfully.");
        message.put("code", 200);

        Map<String, Object> json = new HashMap<String, Object>();
        json.put("success", true);
        json.put("message", message);

        return new ResponseEntity<Map<String,Object>>(message,HttpStatus.CREATED);
    }

当我在PostMan中点击这个方法时,我得到这个错误

org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class java.util.HashMap
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:226)
org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:180)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:82)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:119)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866)
javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

这是我设置应用程序的方式

@Configuration
@ComponentScan("com.fyt.fyt")
@EnableTransactionManagement
public class ApplicationContextConfig {

    @Bean
    public InternalResourceViewResolver getViewResolver() {
        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        internalResourceViewResolver.setPrefix("/WEB-INF/views/");
        internalResourceViewResolver.setSuffix(".jsp");
        return internalResourceViewResolver;
    }

    @Bean
    public DataSource getDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/fyt");
        dataSource.setUsername("root");
        dataSource.setPassword("");
        return dataSource;
    }

    @Bean
    public LocalSessionFactoryBean getSessionFactory() {

        LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
        factoryBean.setDataSource(getDataSource());
        factoryBean.setHibernateProperties(getHibernateProperties());
        factoryBean.setAnnotatedClasses(User.class);
        return factoryBean;

    }

    private Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        return properties;
    }

    @Bean
    public HibernateTransactionManager getTransactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(getSessionFactory().getObject());
        return transactionManager;
    }

    @Bean
    public UserDao userDao() {
        return new UserDaoImpl();
    }
}

错误说,它不能转换列表到httpmessges,所以我需要任何任何转换器或类似的东西?我错过了什么?

2w3rbyxf

2w3rbyxf1#

请在控制器类级别提供**@RestController**,否则请在方法级别提供**@ResponseBody**。请确保类路径中存在所有与Jackson相关的jar。
在pom.xml中添加与Jackson相关的依赖项

@RequestMapping(value = "/user",method = RequestMethod.GET)
@ResponseBody
    public ResponseEntity<Map<String,Object>> handleRequest() throws Exception{
        List<User> users = userService.list();          
        Map<String, Object> message = new HashMap<String, Object>();

        message.put("severity", "info");
        message.put("user", users);
        message.put("summary", "Not successfully.");
        message.put("code", 200);

        Map<String, Object> json = new HashMap<String, Object>();
        json.put("success", true);
        json.put("message", message);

        return new ResponseEntity<Map<String,Object>>(message,HttpStatus.CREATED);
    }

Jackson的pom依赖关系示例。

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.1</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
        </dependency>
jc3wubiy

jc3wubiy2#

对于有类似问题的人:
如果您要传回没有Getter和Setter方法之类别的对象,就会发生这种情况。
例如:如果您有以下设置

public class Employee {
    private int code;
    private String name;
}

并以某种方式使用它:

@GetMapping("")
public ResponseEntity<Employee> getEmployee(@RequestParam("id") Integer id) {
    Employee employee;
    /* CODE. . . 
                */
    return new ResponseEntity<>(employee, HttpStatus.OK);
 }

您可能会收到一个错误消息
异常错误:找不到以下类型的返回值的转换器:异常处理程序
要解决这个问题,只需在employee类中添加getter和setter,问题就解决了!

cotxawn7

cotxawn73#

我认为你需要自定义的httpmessageconvertor。

添加相关性

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

如果此方法不起作用,请尝试在配置文件中为MappingJackson到HttpMessage转换器配置自定义配置。

7rtdyuoh

7rtdyuoh4#

我遇到了类似的错误org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class java.util.ArrayList,即使所有的Jackson依赖项都正确地添加到了我的gradle文件中。我的 Spring 版本是Spring 5.2.3.RELEASE。我把所有的getter和setter都添加到了要添加到集合中的对象中。我尝试了几个版本的jackson-databind,但没有任何帮助。最后,它是我的spring-config.xml中的一行

<mvc:annotation-driven />

帮助我的原始堆栈溢出问题How to return JSON data from spring Controller using @ResponseBody
所有这些都是在我必须将我的应用程序从spring-boot更改为普通的spring-mvc应用程序时开始的。

vfh0ocws

vfh0ocws5#

您可以简单地返回这样的Map和类顶部的user @RestController注解:

@RequestMapping(value = "/user",method = RequestMethod.GET)
    public Map<String,Object> handleRequest() throws Exception{
        List<User> users = userService.list();          
        Map<String, Object> message = new HashMap<String, Object>();

        message.put("severity", "info");
        message.put("user", users);
        message.put("summary", "Not successfully.");
        message.put("code", 200);

        Map<String, Object> json = new HashMap<String, Object>();
        json.put("success", true);
        json.put("message", message);

        message.putAll(json);
        return message;
    }
daolsyd0

daolsyd06#

有类似错误的人,大多数事情都是正确的,试着在API请求中添加这个头!我也遇到过这个问题
Accept : application/json(或您的响应生成的任何媒体)

相关问题