【问题标题】:JSON MediaType in Jersey泽西岛的 JSON MediaType
【发布时间】:2015-01-05 23:41:19
【问题描述】:

我创建了一个使用 REST 服务器进行 CRUD 操作的 WebApp。我使用 java Jersey 和 gradle。 当我进行 POST 操作时,我以 JSON 格式发送对象,如下所示:

ToDo t = new ToDo(...); // Object to be posted
Response response = client.target("http://localhost:8091/todos")
                    .request(MediaType.APPLICATION_JSON)
                    .post(Entity.entity(t, MediaType.APPLICATION_JSON));

但它会抛出异常:

org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json, type=class todos.ToDo, genericType=class todos.ToDo.

我的 build.gradle:

buildscript {
    repositories {
        jcenter()
    mavenCentral()
    }

    dependencies {
        classpath (group: 'com.sahlbach.gradle', name: 'gradle-jetty-eclipse-plugin', version: '1.9.+')
    }
}


apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'jettyEclipse'
apply plugin: 'eclipse'
apply plugin: 'eclipse-wtp'


repositories {
   mavenCentral()                                               
}

dependencies {
   providedCompile 'javax.servlet:javax.servlet-api:3.0.1'
   compile 'org.glassfish.jersey.core:jersey-client:2.3.1'
}

Here my full project

【问题讨论】:

    标签: java json rest jersey jax-rs


    【解决方案1】:

    您将需要一个提供程序来处理 JSON。 JAX-RS 使用MessageBodyReaderMessageBodWriter 来编组和解组不同的内容类型。开箱即用不支持 JSON。我们需要添加一个具有所需提供程序的模块

    我不熟悉 Gradle 和构建文件,以及如何添加依赖项,但使用 Maven,这是 the Jersey User Guide 中提到的依赖项,作为 JSON 绑定支持的首选依赖项

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-moxy</artifactId>
        <version>#{jersey.version}</version>
    </dependency>
    

    更新

    所以看起来使用 Gradle 你只需要添加这个依赖项

    compile: 'org.glassfish.jersey.media:jersey-media-moxy:2.13'
    

    添加后,Jersey 客户端应自动发现/配置提供程序

    【讨论】:

      猜你喜欢
      • 2011-10-14
      • 2014-10-06
      • 1970-01-01
      • 2011-08-02
      • 2012-09-19
      • 1970-01-01
      • 1970-01-01
      • 2016-06-30
      • 2017-05-13
      相关资源
      最近更新 更多