Adam Bien's Weblog

Wednesday Jun 26, 2013

Configuring JAX-RS 2.0 Client For JSON Serialization

JAX-RS 2.0 comes with a standardized client, which is also capable of object serialization / deserialization from JSON format. However, a given JSON implementation needs to be registered first. In the sample below the JSON reference implementation (coming with GlassFish v4) is used:


import javax.json.JsonArray;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import org.glassfish.jersey.jsonp.JsonProcessingFeature;

public class RestClient {

    public JsonArray get() {
        Client client = ClientBuilder.newBuilder().register(JsonProcessingFeature.class)
                .property(JsonGenerator.PRETTY_PRINTING, true).build();
        WebTarget path = this.client.target("…");
		return path.request().get(JsonArray.class);
    }

The dependencies are already located in maven central:


<dependencies>
	<dependency>
		<groupId>org.glassfish.jersey.core</groupId>
		<artifactId>jersey-client</artifactId>
		<version>2.0</version>
	</dependency>
	<dependency>
		<groupId>org.glassfish</groupId>
		<artifactId>javax.json</artifactId>
		<version>1.0</version>
	</dependency>
	<dependency>
		<groupId>org.glassfish.jersey.media</groupId>
		<artifactId>jersey-media-json-processing</artifactId>
		<version>2.0</version>
	</dependency>        
</dependencies>

See you at Java EE Workshops at MUC Airport, especially at the Java EE 7 Delta Day!


Special Events: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014 and Java EE 7: "Testing and Code Quality", 14th October, 2014

A book about rethinking Java EE Patterns

Comments:

Somehow JsonProcessingFeature.class didn't work. I had to use JacksonJaxbJsonProvider.class instead.

Too bad that JSON serialisation doesn't work out of the box with JAXB, since XML and JSON are de facto standard formats for RESTful web services.

Is it possible to print out a JSON string of my annotated POJO? Sometimes the JSON string is malformed, and it would be helpful to see what was sent to the server.

Posted by Duc Luu on July 22, 2013 at 04:34 PM CEST #

There is no build method on Client.

Posted by Leo on August 20, 2013 at 03:19 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
...the last 150 posts
...the last 10 comments
Links
License