Friday, December 30, 2011

JAX-RS Tip of the Day: Automatic Mapping of Jettison JSON Objects

One of the more interesting features in JAX-RS (Jersey) is the ability to automatically "wrap" POJOs. This combined with automatic wrapping of JAXB annotated beans, and using Jackson to create JSON objects is a powerful mix. However, sometimes we want to wrap an object, and add some additional metadata.

This tip is a very simple tip which allows you to create Jettison JSONObject, and JSONArray objects to create new objects, "wrap" existing objects, or add additional metadata. I mention "wrap" the objects, please don't confuse this with JSONP.

To enable automatic POJO mapping, and Jettison objects add the following to the web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<servlet>
    <servlet-name>ServletAdaptor</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <description>
            Allow automatic POJO Mapping features.
        </description>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <description>
            Set the packages to point to resources which you want to allow
            mapping of Jettison based objects. Separate the values for multiple
            packages with a comma (,).
        </description>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.bluelotussoftware.example.jaxrs.resources</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
This simple configuration will give you considerable flexibility in how you handle your objects. This will now allow you to produce JSONObjects like the code example below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@GET
@Path("{id}")
@Produces({MediaType.APPLICATION_JSON})
public JSONObject findJSONObject(@PathParam("id") Integer id) {
    Customer c = super.find(id);
    JSONObject jSONObject = new JSONObject();
    try {
        jSONObject.put("customerId", c.getCustomerId());
        jSONObject.put("name", c.getName());
        jSONObject.put("addressLine1", c.getAddressline1());
        jSONObject.put("addressLine2", c.getAddressline2());
        jSONObject.put("city", c.getCity());
        jSONObject.put("state", c.getState());
        jSONObject.put("phone", c.getPhone());
        jSONObject.put("fax", c.getFax());
        jSONObject.put("email", c.getEmail());
        jSONObject.put("creditLimit", c.getCreditLimit());
    } catch (JSONException ex) {
        throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR);
    }
    return jSONObject;
}

0 comments :

Popular Posts