Question

I am running a REST service on server and I want to convert my List of POJO into Json. I don't want to use @XMLRootElement JA-RX because it is only good for XML. If you Google you will find that Jackson is very good choice for Json.

Is there anyone who have solved this problem and please paste complete Server and Client Code?

Note: I spent 16 hours in just finding out how to do this and when I replied on questions they deleted my answer so I decided to put this here to save others valueable time and I believe in Knowledge sharing.. Please if you can improve my code. I am always open to suggestions.

Was it helpful?

Solution

Detailed Reply includes Server and Client sample implementation with JSON Marshalling and Unmarshalling

Note: Json POJO Mapping features is done using Jackson

I spent a whole day in finidng why message body write was not found. What I was doing wrong is I was using JAXB javax.xml.bind.annotation @XMLRootElement in my Jersey 1.17.1 Web Service and I was trying to unmarshall it with Jackson.

Acutally if you Google it you will find that JAXB is only good for XML but for JSON Jackson is excellent. I also forgot to put some configuration paramters in my web.xml that enable POJO Mapping feature.

Here is the snap of how you your servlet mapping should be to enable POJO mapping feature of Jackson.

<!-- WebService -->
  <servlet>
        <servlet-name>REST Service</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
            <param-value>com.sun.jersey.api.container.filter.LoggingFilter;com.algo.server.webservice.WebServiceRequestFilter</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.algo.server.webservice;org.codehaus.jackson.jaxrs</param-value>
        </init-param>
         <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>REST Service</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

You also need to add those jar files into your WEB-INF/libs folder

  • jackson-core-asl-1.9.2.jar
  • jackson-mapper-asl-1.9.2.jar
  • jackson-xc-1.9.2.jar
  • jackson-jaxrs-1.9.2.jar

This is a sample web service method that returns a list of some objects

    @GET
@Produces({ MediaType.APPLICATION_JSON })
@Path("/clientId/{client_id}/clientDept/{client_department}/clientLoc/{client_location}")
public Response getTasksForClientId(@PathParam("client_id") String pClientId,
        @PathParam("client_department") String pClientDepartment,
        @PathParam("client_location") String pClientLocation) {
    List<Task> list = new ArrayList<Task>(10);
    Task task = null;
    for (int i = 0; i < 10; i++) {
        task = new Task();
        task.setComments("These are test comments");
        task.setCreatedBy(11L);
        task.setCreatedOn(new Date());
        task.setFromDay(new Date());
        task.setFromTime(new Date());
        task.setToTime(new Date());
        task.setToDay(new Date());
        task.setUpdatedOn(new Date());
        task.setLocation("Pakistan Punajb");
        task.setSpecialCoverImage("webserver\\cover\\cover001.png");
        task.setTargetId(1L);
        task.setTargetPlaceHolder(2);
        task.setUpdatedBy(23234L);
        list.add(task);
    }
    GenericEntity<List<Task>> entity = new GenericEntity<List<Task>>(list) {
    };
    return Response.ok(entity).build();
}

Client Side

Now How to use convert this JSON object on client side into same List<T> Object. It's a sinch :-)

You need to put the same class from the server that you converted into POJO. It shoulb be the same

private void checkForUpdate() {
        ClientConfig clientConfig = new DefaultClientConfig();
        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
        clientConfig.getClasses().add(JacksonJsonProvider.class);
        Client client = Client.create(clientConfig);                

        WebResource webResource = client.resource("http://localhost:8080/some-server");

        WebResource wr = webResource.path("rest").path("taskPublisherService").path("clientId/12").path("clientDept/2").path("clientLoc/USA");

        ClientResponse clientResponse = wr.type(MediaType.APPLICATION_JSON).get(ClientResponse.class);

        List<Task> lists = clientResponse.getEntity(new GenericType<List<Task>>() {});

        System.out.println(lists);   

    }

OTHER TIPS

This one from Jersey includes all the above mentioned JARs:

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>${version.jersey}</version>
    <scope>runtime</scope>
</dependency>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top