Jersey + Json media type application/json was not found

╄→гoц情女王★ 提交于 2019-12-17 16:18:46

问题


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.


回答1:


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




回答2:


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/




回答3:


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.




回答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>



回答5:


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).




回答6:


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'
)



回答7:


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.




回答8:


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.




回答9:


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




回答10:


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




回答11:


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>



回答12:


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.




回答13:


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>



回答14:


I tried to download the following jar libraries:

  • jersy-json.jar version 1.19 from MVNrepository,
  • gson version 0.99 from MVNrepository
  • jersey-media-json-jackson-2.15 from MVNrepository
  • jersey-bundle-1.8 from java2s.com

When I download gson 0.99 my rest service work well.




回答15:


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.



来源:https://stackoverflow.com/questions/12179737/jersey-json-media-type-application-json-was-not-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!