1
votes

I'm trying to unmarshal a json response from a REST service into a Java pojo but am unable to do so.

  1. How do I get the response body out of HttpResponse as a string?
  2. How do I get the response body unmarshalled directly into a Java pojo?
  3. Is the GET request made in the below code asynchronous?

I have tried looking into the Akka documentation and other sites but cannot find the answers anywhere.

final Http http = Http.get(actorSystem);
CompletionStage<HttpResponse> response =
    http.singleRequest(HttpRequest.GET("http://127.0.0.1:8081/orders/24"));

HttpResponse httpResponse = response.toCompletableFuture().get();

Order s =
    Jackson.unmarshaller(Order.class)
           .unmarshal(
               httpResponse.entity(),
               ExecutionContexts.global(),
               ActorMaterializer.create(actorSystem)
           ).toCompletableFuture()
           .get();

System.out.println("response body: " + s);               `
1
Not sure why your snippet doesn't work. What error are you getting? - Michal Borowiecki

1 Answers

1
votes

How do I get the response body out of HttpResponse as a string?

In a blocking way (not recommended, but to continue from your code snippet):

HttpResponse httpResponse = response.toCompletableFuture().get();
Strict strict = httpResponse.entity().toStrict(TIMOUT_MS, mat).toCompletableFuture().get();
String body = strict.getData().utf8String();

A better non-blocking way is to do it asynchronously:

response.thenCompose(response ->
    response.entity().toStrict(TIMEOUT, mat)
  ).thenApply(entity ->
    entity.getData().utf8String())
  ).thenApply(body -> 
    // body is a String, do some logic on it here...
  );

The materializer (mat) can be created like so if you don't already have one (the type comes from the akka-stream library, so you'll need a dependency on it):

Materializer mat = ActorMaterializer.create(actorSystem);

How do I get the response body unmarshalled directly into a Java pojo?

Haven't tested this, but should do the trick according to the docs:

Unmarshaller<HttpEntity, Order> unmarshaller = Jackson.unmarshaller(Order.class);

response.thenCompose(response ->
    response.entity().toStrict(TIMEOUT, mat)
  ).thenApply(entity ->
    unmarshaller.unmarshal(entity, mat)
  )

Is the GET request made in the below code asynchronous?

Yes it is. Unless you block on the returned CompletionStage, as you are doing with response.toCompletableFuture().get().