Alex A Alex A - 2 months ago 7
JSON Question

Create business object using JSON processing from JavaEE 7

I am investigating JSON processing from JavaEE 7 and i have a question described below.

(before asking i have read below info but still have a question)

http://docs.oracle.com/javaee/7/tutorial/jsonp004.htm

How can I cast a JSONObject to a custom Java class?

How do I convert a JSONObject to class object?

1) I have a REST web service which returns response in a JSON format:

{"id":1141,"email":"user@organisation.com","enabled":"Y"}


2) There is a corresponding JPA Entity called User

@Table(name = "USER")
@Entity
public class User {

@Id
@Column(name = "USER_ID")
private Long id;

@Column(name = "EMAIL")
private String email;

@Column(name = "ENABLED")
private String enabled;


3) I have a client based on Jersey Client API and Java EE JSON Processing which call this web service.

Maven dependencies:

<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.22.1</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.4</version>
</dependency>


Client code:

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:7001/projectname/rest");
WebTarget resourceWebTarget = target.path("users").queryParam("email", "user@organisation.com");
Invocation.Builder invocationBuilder = resourceWebTarget.request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder.get();

JsonReader reader = Json.createReader(response.readEntity(InputStream.class));
JsonObject jObject = reader.readObject();

User user = new User();
user.setId(jObject.getJsonNumber("id").longValue());
user.setEmail(jObject.getString("email"));
user.setEnabled(jObject.getString("enabled"));


And finally the question:

Should i have create user like
User = new User();
and set all the properties manually or exists more convenient way to create User ?

Answer

At the moment there is no possibility to make direct mapping using simple javax.json-api If you are using Jersey Client API it's better to use Jackson mapper.

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.23.2</version>
    <scope>provided</scope>
</dependency>

You would be able to use such simple construction:

String jsonString = "{'id':1141,'email':'user@organisation.com','enabled':'Y'}";
User user = mapper.readValue(jsonString, User.class);
Comments