Search code examples
jsonjax-rsjava-ee-7jersey-clientjersey-2.0

Read JSON with Jersey 2.0 (JAX-RS 2.0)


I was using Jersey 1.16 to consume a JSON, but now I'm with difficulties to consume a JSON using Jersey 2.0 (that implements JAX-RS 2.0).

I have a JSON response like this:

{
    "id": 105430,
    "version": 0,
    "cpf": "55443946447",
    "email": "maria@teste.br",
    "name": "Maria",
}

and the method that consumes it:

public static JSONObject get() {
   String url = "http://127.0.0.1:8080/core/api/person";
   URI uri = URI.create(url);

   final Client client = ClientBuilder.newClient();
   WebTarget webTarget = client.target(uri);            

   Response response = webTarget.request(MediaType.APPLICATION_JSON).get();

   if (response.getStatus() == 200) {      
      return response.readEntity(JSONObject.class);
   }
}

I also tried:

return webTarget.request(MediaType.APPLICATION_JSON).get(JSONObject.class);

But the jSONObject return is null. I don't understand my error because the response is OK!


Solution

  • This is how to use the Response type correctly:

      private void getRequest() {
        Client client = ClientBuilder.newClient();
    
        String url = "http://localhost:8080/api/masterdataattributes";
        WebTarget target = client.target(url);
    
        Response res = target
            .request(MediaType.APPLICATION_JSON)
            .get();
    
        int status = res.getStatus();
        String json = res.readEntity(String.class);
    
        System.out.println(String.format("Status: %d, JSON Payload: %s", status, json));
      }
    

    If you're just interested in the payload, you could also just issue a get(String.class). But usually you will also want to check the response status, so working with the Response is usually the way to go.

    If you want a typed (generic) JSON response, you could also have readEntity return a Map, or a list of Map if the response is an array of objects as in this example:

    List<Map<String, Object>> json = res.readEntity(new GenericType<List<Map<String, Object>>>() {});
    String id = (String) json.get(0).get("id");
    System.out.println(id);