Search code examples
jsonrestjersey

MessageBodyWriter not found for media type=application/json when returning JSON in REST web service with Jersey


I am trying to create a very simple REST service using Jersey. Here is the service code

@Path("/UserService")
public class UserService {

    @GET
    @Path("/users")
    @Produces(MediaType.APPLICATION_XML)
    public List<User> getUsers() {
        User user = new User(1, "Thomas", "Greene");
        List<User> userList = new ArrayList<User>();
        userList.add(user);
        return userList;
    }
}

When I run it through Postman, it returns me a XML response

XML response in Postman

Now, I want to get a JSON response back. So, I changed the mediatype to application/json:

@Path("/UserService")
public class UserService {

    @GET
    @Path("/users")
    @Produces(MediaType.APPLICATION_JSON)
    public List<User> getUsers(){ 
        User user = new User(1, "Thomas", "Greene");
        List<User> userList = new ArrayList<User>();
        userList.add(user);
        return userList;
   }    
}

It gives me the below error in Tomcat logs:

SEVERE: MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List.

Can someone please guide me how to get a JSON response back?


Solution

  • To use Jackson 2.x as your JSON provider you need to add jersey-media-json-jackson module to your pom.xml file:

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.22.2</version>
    </dependency>
    

    And then register the JacksonFeature in your Application/ResourceConfig subclass.

    For more details, have a look at Jersey documentation.