Requesting an entity and mapping it to a Java class
Consider, for example, you are consuming a REST API which provides the following JSON when performing a GET
request at http://example.com/api/people/1
:
{
"name": "John Doe",
"age": 25
}
The above JSON can be mapped to a Java class, defined as following:
public class Person {
private String name;
private Integer age;
// Constructor, getters and setters omitted
}
Using the JAX-RS Client API, the JSON can be requested as following, mapping the requested entity to the Person
class:
Client client = ClientBuilder.newClient();
Person person = client.target("http://example.com/api")
.path("people").path("1")
.request(MediaType.APPLICATION_JSON)
.get(Person.class);
String name = person.getName();
Integer age = person.getAge();
The JAX-RS Client API is part of the JAX-RS 2.0 specification and the reference implementation is Jersey.
To parse JSON, Jersey comes with a set of extension modules for multiple frameworks that provide support for JSON processing and/or JSON-to-Java binding. Jersey supports MOXy, JSON-P, Jackson and Jettison. For more details, have a look at the documentation.
Parsing the JSON manually
If, for some reason, you need to parse the requested entity manually, you can store the requested entity in a String
:
Client client = ClientBuilder.newClient();
String json = client.target("http://example.com/api")
.path("people").path("1")
.request(MediaType.APPLICATION_JSON)
.get(String.class);
And then the requested entity can be manually parsed using, for example, Jackson:
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(json);
String name = node.path("name").asText();
Integer age = node.path("age").asInt();
To parse the JSON manually, you also could consider Gson.
Alternatives
For alternatives on how to consume REST APIs with Java, have a look at this answer.