每次我尝试调用我的REST服务时,都会收到以下错误消息
[2016-09-01T16:27:37.782+0200] [Payara 4.1] [SEVERE] [] [org.glassfish.jersey.message.internal.WriterInterceptorExecutor] [tid: _ThreadID=28 _ThreadName=http-listener-1(3)] [timeMillis: 1472740057782] [levelValue: 1000] [[MessageBodyWriter not found for media type=application/json, type=class xxx.JsonClass, genericType=class xxx.JsonClass.]]
这是REST服务(剥离到相关部分):
import javax.ejb.EJB;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Path("/service")
public class Service {
@GET
@Path("/callme")
@Produces(MediaType.APPLICATION_JSON)
public JsonClass callme(//
@QueryParam("test") final String test, //
....) {
return new JsonClass();
}
}
JSON类
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
public class JsonClass {
private String test;
public JsonClass(final String test....) {
...
}
@JsonProperty
public String getTest() {
return this.test;
}
}
POM.xml(有趣的部分)
<!-- DO NOT change the scope for jersey: https://java.net/jira/browse/JERSEY-1941 -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.8</version>
<scope>provided</scope>
</dependency>
我的设置是:
-
JDK8 / JEE7(build 1.8.0_51-b16)
-
Glassfish 4.1 Payara
-
Maven 3.2.5
这是我到目前为止所尝试的:
-
MessageBodyWriter not found for media type=application/json - >无法正常工作,因为我遇到了Glassfish 4和Weld(https://java.net/jira/browse/JERSEY-1941)的问题
-
SEVERE: MessageBodyWriter not found for media type=application/json, type=class com.jersey.jaxb.Todo, genericType=class com.jersey.jaxb.Todo - >如上面的POM.xml中所示,它已经包含在内并且不起作用
-
https://java.net/jira/browse/JERSEY-2715 - >注释@Produces已经存在并且也没有帮助
-
Obtaining "MessageBodyWriter not found for media type=application/json" trying to send JSON object through JAX-RS web service - 带有@XmlAttribute的GENSON没有达到预期的效果
-
我试图让JSON对象尽可能简单,以避免数组和复杂对象出现问题 - >无变化
我仍然认为这是一个依赖问题 . 但是我想出了什么可能是问题 .
1 回答
不幸的是,我的上一篇文章被标记为重复,尽管问题和解决方案不同 . 因此,我发布了两个解决方案的新问题,希望能帮助您避免在桌面上敲打几个小时 .
首选解决方案
显然GF4附带了我不想使用的MoxyJson . 要集成您自己的依赖项 - 在我的情况下Jackson - 您需要使用以下代码禁用MoxyJson .
然后添加自己的依赖项,例如在我的情况下只有那两个因为其他人被我使用的另一个lib引用 .
最后我犯了一个错误,即没有为@JsonProperty注释设置一个值,这将导致No MessageBodyWriter发现异常 . 为了避免这种情况,请使用以下ony相关的课程 .
替代方案:
比上面更糟糕的是你需要禁用MoxyJson,单独注册每个服务,并在使用GF的ResourceConfig时修复Bug .
您需要ResourceConfig类的附加依赖项 .
最后与上面相同 - 请注意使用@JsonProperty设置值 .