Create business object using JSON processing from JavaEE 7 Create business object using JSON processing from JavaEE 7 json json

Create business object using JSON processing from JavaEE 7


At the moment there is no possibility to make direct mapping using simple javax.json-apiIf 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);


I think what you're looking for is a constructor method. In your case for the user you have three separate fields which can be populated as soon as you instantiate your User object.

In order to do this add this method (constructor) to your User class:

public User(Long id, String email, String enabled){   this.id = id;   this.email = email;   this.enabled = enabled;}

When creating an instance of the class you will use the following line substituting my hard values for variables of course:

User user = new User(1141, "user@organisation.com", "Y");

For JSON parsing directly into or out of POJOs you might want to take a look into using a library such as Google Gson or Jackson2.

I hope this answers your question!


With the release of JSON Binding in Java EE 8 you can now bind JSON to Java objects.

Here's a simple example:

String userJson = "{\"id\":1141,                    \"email\":\"user@organisation.com\",                    \"enabled\":\"Y\"}";User user = JsonbBuilder.create().fromJson(userJson, User.class);

There is no longer the need to depend on third-party APIs. The JSON Processing and JSON Binding work together and are integrated into the JAX-RS API.

So you can adapt your code example above to the following:

User user = JsonbBuilder.create()              .fromJson(response.readEntity(InputStream.class), User.class);

The JSON-B deserialization process can be customized in a variety of very handy ways with simple annotations or runtime configurations as well as advance lower customization options.