In this post we are going to take JSON retrieved from a Microservice and convert it into a List<POJO> in our Web Client. On the Microservice we'll use Jackson to package the List<POJO> and Jersey to transmit it as a REST Resource in JSON. On the Client we'll use Jersey to handle the Response and Jackson to convert the JSON content back to its original state of List<POJO>.
It's a pretty wild concept, serializing objects, sending them across a wire as a string of characters then somehow ending up with the original objects again on the other side. I'll be performing this magic act in my NixMash Microservices app on GitHub where we have a User REST Microservice and a Web Client. Both share the NixMash Jangles module for data objects and functionality, but otherwise they run as two completely separate applications.
Here is the list offered by the User Microservice endpoint of http://localhost:8000/users.
This is what it will look like when processed on our Web Client at http://localhost:9000/users.
Not much to see on the User Service side. We won't cover the Jackson Annotations on the JanglesUser Object here, but they're an important part of the process. The bound JanglesUser List is then handed off to Jersey for transmission.
On the Client side we're going to read the Jersey Response and convert it to List of Objects with the Jackson TypeFactory. Since we designed getRestList() to be reusable we pass the path to the REST endpoint and the class of the POJO we'll be returning. Notice we're returning a List<?> so that any type extending Object will do.
Here's our method caller:
List<JanglesUser> users = (List<JanglesUser>) getRestList("/users", JanglesUser.class);
The janglesGlobals.userServiceUrl at (1) is an example of sharing the functionality of Jangles across services and the client. It provides a base address in our case of http://localhost:8000 with path being "/users." If the REST endpoint is down we'll throw an Exception (2). We bring Jackson into the picture in (3) where we use a Jackson ObjectMapper to read the Jersey Response String Entity and convert it to a List of clazz objects, or List<JanglesUser>.
Source code discussed in this post is found in NixMash Microservices on GitHub. Code for this particular post is found in branch microservices-v0.1.0 - Initial Layout and Structure.