我试图通过JAX-RS Web服务发送JSON对象.我的文件web.xml是:
JAX-RS Tools Generated - Do not modify JAX-RS Servlet org.glassfish.jersey.servlet.ServletContainer jersey.config.server.provider.packages it.notifire com.sun.jersey.api.json.POJOMappingFeature true 1 JAX-RS Servlet /jaxrs/*
模拟我要发送的对象的类是:
public class GPSCoordinate { private float latitudine; private float longitudine; public float getLatitudine() { return latitudine; } public void setLatitudine(float latitudine) { this.latitudine = latitudine; } public float getLongitudine() { return longitudine; } public void setLongitudine(float longitudine) { this.longitudine = longitudine; } }
根类资源是:
@Path("position") public class Position { @Context private UriInfo context; @GET @Produces(MediaType.APPLICATION_JSON) public GPSCoordinate getHTML() { GPSCoordinate coord = new GPSCoordinate(); coord.setLatitudine(90.45f); coord.setLongitudine(34.56f); return coord; } }
现在,当我尝试访问该服务时,我将浏览器指向以下链接
http://localhost:8080/Notifire/jaxrs/position
我收到以下错误:
消息org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException:找不到媒体类型= application/json的MessageBodyWriter
在我的WEB-INF/lib文件夹中,我有最后一个版本的jersey JAX-RS实现(jaxrs-ri-2.5.jar)和jersey-json.jar存档.
任何帮助将非常感激.
Jersey支持'autodiscoverable'功能,JSON支持就是其中之一.根据文档,为了启用它,您需要在路径中添加兼容的库
但是,虽然由于jersey-media-json-processing
某种原因我的案例中没有识别推荐的库,但是jersey-media-moxy
:
<dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-moxy</artifactId> <version>2.15</version> </dependency>
2.15是撰写本文时的最新版本.访问maven central artifact页面以查找当前版本.
尝试将Genson添加到类路径中,它将自动启用JSON支持.
Genson是json和java/scala的数据绑定和流式库.它实现了JAX-RS的扩展点MessageBodyReader/Writer,允许jersey自动检测Genson并将其用于Json解析/写入.
你可以找到更多关于Gensons与JaxRS(jersey&cie)整合的信息.
向客户端配置注册JacksonJsonProvier类,然后创建Client对象,这对我有用。下面是代码。
ClientConfig config = new ClientConfig(); config.register(JacksonJsonProvider.class); Client client = ClientBuilder.newClient(config);