9

I am using Jersey for REST WS, and I get my response as JSON.

I want to transform this response to a POJO. How to do it ?

Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
Marouane Gazanayi
  • 5,063
  • 6
  • 39
  • 58

5 Answers5

10

To convert between Java and JSON, there are a good number of APIs available to choose from.

You could "manually" step through the JSON components and extract values to populate Java objects, or you could use a JSON-to-Java binding API to take care of many low-level mapping concerns.

Jackson is such an API. It's easy to use and provides probably the fullest set of API features to address common issues and customizations. StackOverflow.com has many examples of how to use it.

Tom
  • 16,842
  • 17
  • 45
  • 54
Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97
  • I'm doing this : WebResource resource = client.resource(urlStr); resource.accept(MediaType.APPLICATION_JSON); GenericType> genericType = new GenericType>() {}; List response = null; try{ response = resource.get(genericType); } catch (UniformInterfaceException ue) { ClientResponse clientResponse = ue.getResponse(); } But I got this error : GRAVE: A message body reader for Java class java.util.List, and Java type ... was not found – Marouane Gazanayi Jun 21 '11 at 14:36
  • 2
    I recommend posting this in a new question. The more information about the error message, the specific line of code that caused it, and the values of relevant components at the time of error, the better. – Programmer Bruce Jun 21 '11 at 14:44
  • Did it :) http://stackoverflow.com/questions/6427478/error-when-trying-to-convert-json-to-pojo-using-jersey – Marouane Gazanayi Jun 21 '11 at 15:03
1

As an option, you can check JSON Simple.

weekens
  • 8,064
  • 6
  • 45
  • 62
0

You can also use JaxB binding which would handle conversion to and from for you. Its part of Java SE so no jar downloads required.However, you would need to write a pojo class with all the attributes your json object will return and accessor methods to assess them. Then you would add a XmlRootElement annotation on that class this will enable jaxb to convert to and from json where necessary. Example:

POJO

 @XmlRootElement
public class User
{
    private String name;

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

   public String getName ()
   {
       return name;
   }

}

Jersey service

 @GET
 @Produces (MediaType.APPLICATION_JSON)
 public User getUser ()
 {
     User user = new User ();
     user.setName ("John Doe");
     return user;
 }

This would convert the User POJO object and return it has the media type specified in this example JSON. You can even return it with a Response object. Example:

  @GET
 @Produces (MediaType.APPLICATION_JSON)
 public Response getUser ()
 {
     User user = new User ();
     user.setName ("John Doe");
     return Response.status (Status.OK).entity (user).build ();
 } 

This returns a Response object with code 200 (Success) along with User JSON object. [NOTE] This approach is preferred cause It provide the user who invokes your web service information about the status of the transaction or service

Mario Dennis
  • 2,986
  • 13
  • 35
  • 50
0

We can also make use of below given dependency and plugin in your pom file.

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>1.7.1</version>
</dependency>

<plugin>
    <groupId>com.googlecode.jsonschema2pojo</groupId>
    <artifactId>jsonschema2pojo-maven-plugin</artifactId>
    <version>0.3.7</version>
    <configuration>
        <sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory>
        <targetPackage>com.example.types</targetPackage>
    </configuration>
    <executions>
        <execution>
            <phase>generate-sources</phase>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>

With the use of these you can generate POJO's as per your JSON Schema and then make use of code given below to populate request JSON object via src object specified as parameter to gson.toJson(Object src):

Gson gson = new GsonBuilder().create();
String payloadStr = gson.toJson(data.getMerchant().getStakeholder_list());
Sylhare
  • 5,907
  • 8
  • 64
  • 80
akshaymani
  • 623
  • 5
  • 10
0

Was looking for the same and since others require you to add annotations or write/generate getter and setter methods for your variables, I wrote my own codec to deal with JSON<->POJO transformations using reflections.

See here: http://homac.cakelab.org/projects/org.cakelab.json

homac
  • 391
  • 3
  • 7