0

I'm doing exercises with Spring-Boot, I tried to search, but nothing I've found worked for me. I'm trying to return a JSON converting a POJO, which SB is supposed to do it automatically, but it returns:

2018-11-05 13:26:36.090 WARN 1584 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class com.example.demo.pelis.Foo]

Here is my pom.xml:

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

And my POJO:

public class Foo {

    private String bar;

    /**
     * @return the bar
     */
    public String getBar() {
        return bar;
    }

    /**
     * @param bar
     *            the bar to set
     */
    public void setBar(String bar) {
        this.bar = bar;
    }
}

The controller:

@RestController
public class PelisController {
    @GetMapping(value = "/fooPoint")
    public Foo fooPoint() {
        Foo foo = new Foo();
        foo.setBar("smthng");
        return foo;
    }
}

I don't know what I'm doing wrong, because I've tried getters/setters method, I tried to replace my pom with the one in the official guide. Nothing helped.

mariotepro
  • 119
  • 1
  • 2
  • 8

5 Answers5

7

I just encountered this issue today and spent several hours to figure out what the issue is. Almost all of the answers I've seen are either because of missing getters and setters, adding the fasterxml dependency into the pom. I already have getters and setters and the tutorial I was following did not require those pom changes.

mariotepro's solution is what got me past the issue. His solution is buried under the comments so I decided to put it here in the answer so people can easily see it in case they have the same scenario.

So yes, just to reiterate, going into my maven repo and deleting the fasterxml folder and re-running maven is what fixed the issue for me.

jax502
  • 173
  • 1
  • 2
  • 9
1

I think that besides getters and setters you need a default empty contructor, so adding just that should make it work. An easy way to add that and the get and set methods to so called data classes is to use project Lombok.

An example can be found here:

https://github.com/mstine/todo-list/blob/master/src/main/java/io/pivotal/sporing/todos/todolist/TodoItem.java

So you basically add the dependency in Maven like:

<!-- For Lombok, data annotations -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

Then you can use the annotations in the class like (snippet):

import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Entity
@Data
@NoArgsConstructor
@Table(name="todo_item")
public class TodoItem {
    @Id
    @GeneratedValue
    private Long id;

The annotations: @Data and @NoArgsConstructor create the getters, setters and the empty constuctor, which saves you the boiler plate code, which I think is quite neat :).

Here is some more info if you're interested: https://projectlombok.org/

Dharman
  • 30,962
  • 25
  • 85
  • 135
Vincent Gerris
  • 7,228
  • 1
  • 24
  • 22
0

As of Spring Boot 2.5.7 getters or fasterxml don't solve this problem, but setting produces in @RequestMapping does try setting produces = { "application/json" }

@RequestMapping(method = RequestMethod.GET, produces = { "application/json" })
0

People with similar errors, I was just missing below header while hitting the Request, try adding to check if it works!

Accept : application/json

Harsh
  • 812
  • 1
  • 10
  • 23
0

For me this happend when i didnt specify headers with content-type following is the code

Model class - UserModel.java

@Data 
public class UserModel {
    
    private String username;
    private long userid;

}

set up lombok using this link

controller class - BasicController.java

@RestController
public class BasicController {

    ArrayList<UserModel> users = new ArrayList<>();
    
    @PostMapping(
            path="/push/user", 
            produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}, 
            consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}
    )
    public ResponseEntity<UserModel> pushUser(@RequestBody UserModel user)
    {
        System.out.println(user.getUsername());
        System.out.println(user.getUserid());
        
        users.add(user);
        return new ResponseEntity<UserModel>(user, HttpStatus.OK);
    }
    
}

following error when i sent data without headers

enter image description here

 {"timestamp": "2022-11-06T05:35:00.356+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "trace": "org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class com.sp.learner.code.api.controller.UserModel] with preset Content-Type 'null'\n\tat org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:312)\n\tat org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:219)\n\tat org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:78)\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:135)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1071)\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:964)\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:696)\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:779)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789)\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\n\tat java.base/java.lang.Thread.run(Thread.java:832)\n",
    "message": "No converter for [class com.sp.learner.code.api.controller.UserModel] with preset Content-Type 'null'",
    "path": "/push/user"
}

solution - adding headers as following

enter image description here

Parameshwar
  • 856
  • 8
  • 16