Alex A Alex A - 27 days ago 5x
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)

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:


2) There is a corresponding JPA Entity called User

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

@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:



Client code:

Client client = ClientBuilder.newClient();
WebTarget target ="http://localhost:7001/projectname/rest");
WebTarget resourceWebTarget = target.path("users").queryParam("email", "");
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();

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 ?


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.


You would be able to use such simple construction:

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