Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

rest

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?

like image 826
kayasa Avatar asked May 16 '16 08:05

kayasa


1 Answers

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.

like image 134
cassiomolin Avatar answered Oct 03 '22 12:10

cassiomolin