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!

有帮助吗?

解决方案

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);

其他提示

I have found the solution. Maybe it is not the best of, but it works.

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();

  //Se Response.Status.OK;
  if (response.getStatus() == 200) {
     StringReader stringReader = new StringReader(webTarget.request(MediaType.APPLICATION_JSON).get(String.class));
     try (JsonReader jsonReader = Json.createReader(stringReader)) {
        return jsonReader.readObject();
     }
  }

  return null;

}

I switched the class JSONObject (package import org.codehaus.jettison) by JsonObject (package javax.json) and I used the methods to manipulate the content as String.

S.

mmey answer is the correct and optimal one, instead of invoking the service twice it does it one time.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top