Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAX-RS - JSON without root node

Tags:

java

json

jax-rs

I have a restful web service, and the response is:

{
    "cities": [{
        "id": "1",
        "name": "City 01",
        "state": "A1"
    }, {
        "id": "2",
        "name": "City 02",
        "state": "A1"
    }]
}

But I want this:

{
    [{
        "id": "1",
        "name": "City 01",
        "state": "A1"
    }, {
        "id": "2",
        "name": "City 02",
        "state": "A1"
    }]
}

How I can configure JAX-RS to produces JSON without root node using only JAX-RS feature, and not implementation specific feature? My code needs to be portable across any appserver.

like image 541
Otávio Garcia Avatar asked Jan 29 '11 17:01

Otávio Garcia


1 Answers

I had the same problem with Glassfish v3. I found this behavior depends on the JAX-RS implementation and switching to Codehaus' Jackson JAX-RS implementation solved the problem for me.

If you're using Glassfish as well, then you can solve the problem by adding org.codehaus.jackson.jaxrs to your war as well as to the WEB-INF/web.xml configuration as follows:

<!-- REST -->

<servlet>
  <servlet-name>RESTful Services</servlet-name>
  <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
  <init-param>
    <param-name>com.sun.jersey.config.property.resourceConfigClass</param-name>
    <param-value>com.sun.jersey.api.core.PackagesResourceConfig</param-value>
  </init-param>
  <init-param>
    <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>you.service.packages;org.codehaus.jackson.jaxrs</param-value>
    <!-- NOTE: The last element above, org.codehaus.jackson.jaxrs, replaces the default
       JAX-RS processor with the Codehaus Jackson JAX-RS implementation. The default
       JAX-RS processor returns top-level arrays encapsulated as child elements of a
       single JSON object, whereas the Jackson JAX-RS implementation return an array.
    -->
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>RESTful Services</servlet-name>
  <url-pattern>/your/rest/path/*</url-pattern>
</servlet-mapping>

Alternatively, you might be able to simply intercept the response in the client:

function consumesCity(json) {
   ...
}

Replace

... consumesCity(json) ...

with

function preprocess(json) {
    return json.city;
}

... consumesCity(preprocess(json)) ...
like image 66
Kim Burgaard Avatar answered Sep 28 '22 05:09

Kim Burgaard