0

I've some Spring Boot applications (as microservices) each one with a Repository like:

@RepositoryRestResource(collectionResourceRel = "cart", path = "cart")
@CrossOrigin
public interface CartRepository extends PagingAndSortingRepository<Cart, Long> {

When I save a "Cart" entity, a @RepositoryEventHandler class sends the entity as a json string to an Apache Kafka topic:

@HandleAfterCreate
public void handleAfterCreate(final Cart cart) throws JSONException, JsonProcessingException {
    final JSONObject json = new JSONObject(mapper.writeValueAsString(cart));
    json.put("eventType", "saved");
    sender.send(json.toString());
}

Finally, another Spring Boot application consumes the Kafka's topic. Here, I get some related information by calling RestTemplate.getForObject(...) on other microserivces.

String templateURL="http://localhost:6060/api/cart/{id}/articles";
Map<String, Long> parameters = new HashMap<>();
parameters.put("id", cartId);
String result = restTemplate.getForObject(templateURL, String.class, parameters);
JSONObject obj = new JSONObject(result);

The obj contains something like:

{"_embedded":{"articles":[{"id":1},{"id":2}]},"_links":{"self":{"href":"http://localhost:7074/api/cart/1/articles"}}}

But I can't find a way to get all the articles from that json.

I tried with:

Object articles = obj.get("articles");

But it doesn't work. I've already seen other answer like this or similar, but I can solve my problem.

So, how can I get a JSONArray from a RepositoryRestResource by RestTemplate?

Thanks

Alessandro
  • 4,382
  • 8
  • 36
  • 70
  • 1
    Shouldn't you call get("_embedded") first, then get("articles") ? – Lukas Bradley Dec 05 '17 at 17:28
  • Yes of course, but I'm wondering if it's possible to avoid the "_embedded" node or what's the clearest way to read that data... anyway I think I will do it in that way. Thank you. – Alessandro Dec 06 '17 at 08:20
  • Take a look at this: https://stackoverflow.com/questions/27405637/meaning-and-usage-of-embedded-in-hateoas – Lukas Bradley Dec 06 '17 at 13:54

0 Answers0