17

I am trying with simple Jersey + JSON example but I get following error message body writer for Java class com.test.jsonexample and MIME media type application/json was not found

I put following jar files for getting appropriate result

asm-3.1.jar
jackson-core-asl-1.9.9.jar
jackson-jaxrs-1.9.9.jar
jackson-mapper-asl-1.9.9.jar
jackson-xc-1.9.9.jar
jersey-client-1.9.jar
jersey-core-1.9.1.jar
jersey-json-1.9.jar
jersey-server-1.9.1.jar
jettison-1.3.2.jar
jsr311-api-1.1.1.jar

Why am I am getting this type of error? The error log is here:

SEVERE: Mapped exception to response: 500 (Internal Server Error)
javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class com.test.Jsonexample, and Java type class com.test.Jsonexample, and MIME media type application/json was not found
    at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:285)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1437)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:708)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>TestJaxRs</display-name>

    <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.test.rest</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

JsonExample.java

@XmlRootElement  
public class JsonExample {

    String title;
    String singer;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSinger() {
        return singer;
    }

    public void setSinger(String singer) {
        this.singer = singer;
    }

    @Override
    public String toString() {
        return "JsonExample [title=" + title + ", singer=" + singer + "]";
    }

}

and the Json Service

@Path("/json/metallica")
public class JSONService {

    @GET
    @Path("/get")
    @Produces(MediaType.APPLICATION_JSON)
    public JsonExample getTrackInJSON() {

        JsonExample json = new JsonExample();
        json.setTitle("Enter Sandman");
        json.setSinger("Metallica");

        return json;

    }

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createTrackInJSON(JsonExample track) {

        String result = "Track saved : " + track;
        return Response.status(201).entity(result).build();
    }

Please suggest me if I am doing something wrong.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Ajay
  • 4,850
  • 2
  • 32
  • 44

15 Answers15

15

This problem is fixed with jersey-bundle-1.8.jar

Ajay
  • 4,850
  • 2
  • 32
  • 44
  • 2
    I included artifact "jersey-json" in my pom.xml and it solved my problem. In non-maven project, you could solve the issue by including "jersey-json.jar" file in the classpath. – Hemant G Aug 14 '13 at 12:20
  • 1
    adding "jersey-json" API solves the problem. com.sun.jersey jersey-bundle 1.18.1 – Ahmet Karakaya Jun 17 '14 at 08:19
  • gradle : compile "com.sun.jersey:jersey-bundle:1.18.1" – Lau Llobet Jun 25 '18 at 14:54
  • @Ajay - please mention in your answer that jersey bundle should exist without any other jersey dependency (client, server, core, etc.) Forgetting other jersey dependency can produce unknown behavior - it happened to me. No errors were reported but by some reason, the object was not serialized and empty body was sent on the request. – Victor Jul 20 '18 at 12:49
  • i got the same issue, i was becose i didn't put my 'response(entity.toString).build.' The 'toString' is the key – Big Zed Dec 08 '19 at 02:44
10

Fixed issue by adding the following to my pom.xml:

    <dependency>
        <groupId>com.owlike</groupId>
        <artifactId>genson</artifactId>
        <version>0.99</version>
    </dependency>

Documentation can be found at: https://code.google.com/p/genson/

wingman88
  • 151
  • 2
  • 3
4

First of all if your @POST web-service returns a response you must add @Produces annotation.

Ensure that jersey-json lib is in your classpath. Try removing the toString() method because it may broke the beans structure format.

Alex Stybaev
  • 4,623
  • 3
  • 30
  • 44
4

Add the following dependency to solve the problem

"javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class com.test.Jsonexample, and Java type class com.test.Jsonexample, and MIME media type application/json was not found
    at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:285)"

Solution :

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-bundle</artifactId>
    <version>1.18</version>
</dependency>
SkyWalker
  • 28,384
  • 14
  • 74
  • 132
Hari
  • 41
  • 1
3

If you are not tied to jackson you could try Genson library http://owlike.github.io/genson/. You only need the lib in your classpath and every thing should work without any additional code. You wont even have to use POJOMappingFeature in web.xml nor add @XMLRootElement on your pojo!

You can also inject instances of Genson with specific configurations using jersey mechanisms (ContextResolver).

eugen
  • 5,856
  • 2
  • 29
  • 26
3

Tried with 'com.sun.jersey:jersey-bundle:1.19' and it did not solve.

Setting the dependency on genson resolved for me.

runtime(
        'com.owlike:genson:0.99'
)
SkyWalker
  • 28,384
  • 14
  • 74
  • 132
nashter
  • 1,181
  • 1
  • 15
  • 33
3

I've spent literally 4 days on this and after googling for hours and hours why my POST wasn't working at all. I was getting this error as well as other errors to do with MOXY such as classdefnotfound error, due to people on stackoverflow suggesting to use MOXY instead of Jackson. I also tried the genson library which provided no difference whatsoever either.

I ended up completely removing MOXY and only keeping Jackson. After hours I finally found the solution, which made me angry a little bit due to how simple it was. My workspace is separated into multiple different projects, one for the webapplication which holds web.xml and another for the RESTful API.

I'm also running Jersey 2, which was another problem as a lot of the accepted answers for this problem only talked about Jersey 1 and it was super confusing when I was first trying to solve this.

After hours and hours of trying it ended up coming down to this (using the structure of code that was posted in OP):

  1. You HAVE to include @XmlRootElement at the top of your POJO class, contrary to many of the examples on stackoverflow which seem to omit it.

  2. You HAVE to include the following in both the project that includes your web.xml as well as the project that includes your REST service and associated classes. Change the version which is relevant to version of Jersey you are using.

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

That's it. You don't need to include anything else besides this and the relevant Jersey libraries which you are using.

I seriously hope this helps someone else save hours of time trying to troubleshoot this.

Toofy
  • 804
  • 9
  • 19
2

When using jersey-bundle-1.19.1.jar (non-maven) I had to remove this:

<init-param>
  <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
  <param-value>true</param-value>
</init-param>

from web.xml file.

I know that documentation suggests this section is necessary but surprisingly it was a reason of the problem.

David Guyon
  • 2,759
  • 1
  • 28
  • 40
jakucki
  • 21
  • 1
1

I had the same problem and I fixed it with removing all json dependencies and adding com.owlike genson 0.99

1

I know this is an old question, but I came across this issues and tried all the above solutions, but unfortunately, none of them helped me. What I found was, that the class MediaType was defined in two different jars, and when building the jar, it took the class that was defined in the other class (in my case, glassfish jar). After removing the other jar (you can also exclude the specific part), the problem was solved

Inbal
  • 281
  • 2
  • 13
  • It makes sense. We got the same issue. It worked with jersey-bundle BUT, the real problem was a dependency conflict between jersey modules. – Danilo Gomes May 04 '16 at 14:33
1

I tried to download the following jar libraries:

When I download gson 0.99 my rest service work well.

Jorge Santos
  • 397
  • 4
  • 3
0

For new version of Maven, if you have dependency problems, here is a good official reference: https://jersey.java.net/documentation/latest/modules-and-dependencies.html#d0e383 (Section 2.3.1, 2.3.2)

And also here is a good tutorial for installing maven and tuto of Jersey in eclipse: http://javaposts.wordpress.com/2012/01/14/maven-rest-jersey-eclipse-tutorial/

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
</dependency>
<!-- if you are using Jersey client specific features -->
<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
</dependency>
dellgg
  • 464
  • 4
  • 11
0

Also check the actual type parameter of the post method.

Having also gson as a dependency, i should be using JSONObject (Jettison from Jersey-Json) in stead of JsonObject (gson), which resulted in the same exception.

user2657714
  • 1,134
  • 1
  • 8
  • 7
0

Include this dependencies in your POM.xml and run Maven -> Update

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>1.18.1</version>
</dependency>
<dependency>
   <groupId>com.owlike</groupId>
   <artifactId>genson</artifactId>
   <version>0.99</version>
</dependency>
borchvm
  • 3,533
  • 16
  • 44
  • 45
0

I too have same issue with 1.19.4 jersey. It got fixed by adding

compile group: 'com.fasterxml.jackson.jaxrs', name: 'jackson-jaxrs-json-provider', version: '2.10.0.pr1'

to gradle dependency.

Thanks, Praveen R.

Ravipati Praveen
  • 446
  • 1
  • 7
  • 28