Tuesday Jul 23, 2013

JSON Binding with JAX-RS - Moxy, JSON-P, Jackson, Jettison (TOTD #214)


One of the typical questions asked during presentations is how do I enable JSON support in JAX-RS ?

There are three basic approaches and four different modules in Jersey that enable them. Here is a quick summary:


MOXy
JSON-P
Jackson
Jettison
POJO-based JSON Binding
Yes
No
Yes
No
JAXB-based JSON Binding
Yes
No
Yes
Yes
Low-level JSON parsing & processing
No
Yes
No
Yes

MOXy is the default and preferred way of supporting JSON binding in your Jersey applications. A new sample is now added at:

https://github.com/arun-gupta/javaee7-samples/tree/master/jaxrs/moxy

The resource definition is:

@Path("endpoint")
public class MyResource {
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public MyObject echoObject(MyObject mo) {
        return mo;
    }
}


POJO is defined as:

public class MyObject {

    private String name;
    private int age;

    public MyObject() {
    }

    public MyObject(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Application class is:

@ApplicationPath("webresources")
public class MyApplication extends Application {
}

And the client code is:

Client client = ClientBuilder.newClient();

WebTarget target = client.target("http://"
        + request.getServerName()
        + ":"
        + request.getServerPort()
        + request.getContextPath()
        + "/webresources/endpoint");
System.out.println("POST request");
MyObject mo = target
        .request()
        .post(Entity.entity(new MyObject("Duke", 18), MediaType.APPLICATION_JSON), MyObject.class);
out.println("Received response: " + mo.getName() + ", " + mo.getAge() + "<br><br>");

JSON MOXy module (jersey-media-moxy.jar) is in your classpath then Jersey automatically discovers the module and enable JSON binding support via MOXy.

jersey.java.net/documentation/latest/media.html provide more details on all the approaches and modules.

Monday Dec 24, 2007

Santa's Goodie Bag for Developers

Merry Christmas!

And guess what, Santa has been delivering gifts through out December:
Have you not tried any of these ?

And of course, you can get nightly builds for each of these technologies :)

Technorati: glassfish netbeans jruby ruby metro grizzly jaxb jmaki
About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today