Wednesday, February 5, 2014

Using JSON-P, aka JSR 353 with Jersey 1.x, or indeed any JAX-RS 1.x

I have been playing with JSON-P a little bit recently and one of the thing I wanted to try as making it work with Jersey 1.x. (Jersey 2.x has this functionality built in).

I had hoped to use the org.glassfish:jsonp-jaxp component that comes from the json-p project; but it depends on the JAX-RS 2.0 API. With a bit of friendly badgering of the ever helpful Pavel Bucek, a version was published that would work with JAX-RS 1.x implementations.

If you are a maven user this would be as simple as adding the following dependencies:

<dependency>
      <groupId>org.glassfish</groupId>
      <artifactId>javax.json</artifactId>
      <version>1.0.4</version>
    </dependency>
    <dependency>
      <groupId>org.glassfish</groupId>
      <artifactId>jsonp-jaxrs-1x</artifactId>
      <version>1.0</version>
    </dependency>

Otherwise you can easily just download the two files from here and here and add them to your project.

Then you can consume and produce JsonStructure (JsonObject and JsonArray) elements to your hearts content, using the helper methods from the previously mentioned post:

@Path("/hello")
public class Hello {

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public JsonStructure hello() {

    return JsonObjectBuilder builder =
      ob()
       .add("hello", "world")
       .add("fark", ".com")
       .add("fish", ob()
         .add("child", "child"))
       .add("array", ab()
         .add("one")
         .add("two")
         .add(ob()
           .add("boolean",
           true))).build();
  }


}



No comments: