Javier Tello
Javier Tello

Reputation: 47

JSON MediaType in Jersey

I've created a WebApp that make CRUD operations using a REST server. I use java Jersey and gradle. When I do a POST operation, I send the object in JSON format, as follows:

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

But it throws an exception:

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

My 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

Upvotes: 3

Views: 1208

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208974

You're going to need a provider to process the JSON. JAX-RS uses MessageBodyReader and MessageBodWriter to marshal and unmarshal different content types. JSON isn't supported out the box. We need to add a module that has the needed provider(s)

I'm not familiar with Gradle and and build file, and how to add dependencies, but with Maven, this is the dependency mentioned in the Jersey User Guide as the preferred dependency for JSON binding support

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

UPDATE

So it looks like with Gradle you just need to add this dependency

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

With this added, the provider should be auto discovered/configured by the Jersey Client

Upvotes: 3

Related Questions