Skip to content
Advertisement

Get object from .readEntity

I have a java service which calls an API and gets the following in return

{
  "status": {
    "service1": {
      "available": true,
      ...
    },
    "service2": {
      "available": false,
      ...
    },
    ...
  }
}

How can i use .readEntity (or something else) to get the object for a given field; say service2

Or just convert all objects inside status to a List<> of objects

String output = response.readEntity(String.class); works, but i dont know how to parse it properly to something useful as i dont want to search in the string

import javax.ws.rs.client.Client;
import javax.ws.rs.core.Response;

Response response = client
        .target(url)
        .request()
        .get();

String output = response.readEntity(String.class);

Advertisement

Answer

You can model the data with a POJO and use that to extract the data. A model of the JSON that you’ve posted might look something like

public static class ResponseData {
    private Map<String, Service> status;

    // getters and setters

    public static class Service {
        private boolean available;

        // getters and setters
    }
}

The getters and setters should use JavaBean naming convention. Then make sure you have a JSON provider such as Jackson

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>${jersey2.version}</version>
</dependency>

Now you can simply pass the POJO class to the readEntity() method and it will deserialize the JSON into your POJO class.

ResponseData resData = res.readEntity(ResponseData.class);
Service service2 = resData.getStatus().get("service2");

For more details on modeling your JSON, you can do a Google search for “data binding with Jackson”

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement