Search code examples
javaspringclientspring-hateoas

Read hateoas response with embedded HAL collection with spring


I'm trying to read a REST HATEOAS response like this one :

{
  "_embedded": {
    "tasks": [
      {
        "id": 1,
        "name":"task1"
        "_links": {
          "self": {
            "href": "http://localhost:8080/v1/tasks/1"
          },
          "tasks": {
            "href": "http://localhost:8080/v1/tasks"
          }
        }
      }
    ]
  },
  "_links": {
    "self": {
      "href": "http://localhost:8080/v1/tasks?page=0&size=1"
    }
  },
  "page": {
    "size": 1,
    "totalElements": 1,
    "totalPages": 1,
    "number": 0
  }
}

I'm trying to folloaw the example of spring's documentation : spring hateoas traverson.

Java code :

...
TypeReferences.ResourcesType<Resources<Task>> resourceParameterizedTypeReference = new TypeReferences.ResourcesType<Resources<Task>>(){};

Traverson traverson = new Traverson(new URI("http://localhost:8080/v1/tasks"), MediaTypes.HAL_JSON);

Traverson.TraversalBuilder builder = traverson.follow(rel("tasks")).withHeaders(headers);

Resources<Resources<Task>> taskResources = builder.toObject(resourceParameterizedTypeReference);
...

But I obtain this error :

Did not find LinkDiscoverer supporting media type text/html!

Cause : "follow(rel("tasks"))" don't find "tasks".

I'm trying other solutions like this one : Deserialize JSON containing (_links and _embedded) using spring-hateoas, I obtain the error "Expected to find link with rel ..." too.

Maybe finaly I'm not understand the good manner to use traverson object.

I solve my problem by parsing myself the response in Json, but are they another way to get the list contains in the "_embedded" tags in a list of beans ?

If you have some examples I'm interesting :).


Solution

  • I think you need to use a Json Path expression to access the embedded content.

    Traverson.TraversalBuilder builder = traverson.follow("$._embedded.tasks[0]").withHeaders(headers);
    
    Resources<Resources<Task>> taskResources = builder.toObject(resourceParameterizedTypeReference);
    

    The following tool is useful for playing with the path expression: http://www.jsonquerytool.com/

    BTW, your JSON is missing a "," after the "name".