我正在尝试使用以下代码片段从http://api.openweathermap.org/data/2.5/forecast/daily?lat=35&lon=139&cnt=10&mode=json接收json数据:
private WebTarget getWebTarget() {
Client client = JerseyClientBuilder.newClient();
return client.target("http://api.openweathermap.org/")
.path("data")
.path("2.5");
}
// new one method
Response response = getWebTarget()
.path("daily")
.queryParam("q", String.format("%s,%s", town, countryCode))
.queryParam("cnt", 10)
.queryParam("mode", "json")
.request().accept(MediaType.APPLICATION_JSON_TYPE).get();
WeatherForecast forecast = response.readEntity(WeatherForecast.class);
但最后一行抛出:
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException:找不到媒体类型= application / octet-stream的MessageBodyReader,类型=类com.app.weather.providers.org.openweathermap.pojo.WeatherForecast,genericType = class com . app.weather.providers.org.openweathermap.pojo.WeatherForecast .
pom.xml中的Jersey依赖项:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.4</version>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json</artifactId>
<version>2.0-m05-1</version>
</dependency>
此代码在应用程序服务器之外运行 . 谢谢 .
3 回答
Jersey JSON支持作为一组扩展模块提供,其中每个模块都包含需要注册到
Configurable
实例(客户端/服务器)的Feature
的实现 . 有多个框架为JSON处理和/或JSON到Java绑定提供支持 . 下面列出的模块通过将各个JSON框架集成到Jersey中来提供对JSON表示的支持 . 目前,Jersey集成了以下模块以提供JSON支持:MOXy - 通过MOXy的JSON绑定支持是自Jersey 2.0以来在Jersey应用程序中支持JSON绑定的默认和首选方式 . 当JSON MOXy模块位于类路径上时,Jersey将自动发现模块并通过MOXy在应用程序中无缝启用JSON绑定支持 . (参见第4.3节“自动发现功能” . )
用于JSON处理的Java API(JSON-P)
Jackson
Jettison
欲了解更多信息,请阅读chapter 9的球衣文件 .
Moxy是json媒体支持的提议方法 . MOXy媒体模块是您无需在客户端/服务器中明确注册其功能(MoxyJsonFeature)的模块之一可配置,因为当您将jersey-media-moxy模块添加到类路径时会自动发现并注册此功能 .
要将MOXy用作JSON提供程序,您需要将jersey-media-moxy模块添加到pom.xml文件中:
如果你没有使用Maven,请确保拥有所有必需的依赖项 . 见jersey-media-moxy dependencies .
您需要将这些jar文件添加到项目中,以便通过jersey-media-moxy支持json媒体类型:
jersey-media-moxy-2.15.jar
org.eclipse.persistence.core-2.5.0-rc2.jar
org.eclipse.persistence.antlr-2.5.0.jar
org.eclipse.persistence.moxy-2.5.0.jar
jersey-entity-filtering-2.3.1.jar
用法:
一些普通班:
以及运行泽西客户端示例的主要类:
服务器的json响应(
http://localhost:8084/myhost/test
)必须采用以下格式:通过编写自定义MessageBodyReader解决 . https://jersey.java.net/documentation/latest/message-body-workers.html#d0e4072
我遇到了类似的问题,试着用媒体类型“application / javascript”解组JSON . 我只想为原始答案做出贡献,举例说明我如何实施建议的解决方案 . 您可以根据需要更改介质类型 .