user1648825
user1648825

Reputation: 999

Spring boot data rest findby traverson to java object

my URI is http://localhost:8080/context/my-objects/search/findByCode?code=foo

JSON response:

{
  "_embedded" : {
    "my-objects" : [ {
      "code" : "foo",
      "description" : "foo description",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/context/my-objects/34"
        }
      }
    } ]
  }
}

How can I get a java MyObject with Traverson or RestTemplate?

import org.springframework.hateoas.ResourceSupport;

public class MyObject extends ResourceSupport{

    private String code;

    private String description;

    public String getDescription() {
        return description;
    }

    public void setDescription(final String description) {
        this.description = description;
    }

    public String getCode() {
        return code;
    }

    public void setCode(final String code) {
        this.code = code;
    }

}

This is my Template. I've also tried with a default one.

{
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.registerModule(new Jackson2HalModule());

MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json"));
converter.setObjectMapper(mapper);

RestTemplate template = new RestTemplate(Collections.<HttpMessageConverter<?>> singletonList(converter));

}

Thx in advance.

Upvotes: 3

Views: 3990

Answers (1)

user1648825
user1648825

Reputation: 999

I've found the solution. First, create a Resources class:

import org.springframework.hateoas.Resources;

public class MyObjects extends Resources<MyObject> { }

Then it is straightforward:

MyObjects myObjects = template.getForObject("http://localhost:8080/context/my-objects/search/findByCode?code=foo", MyObjects.class);

Attention: the template should support hal+json Media Type.

Or with Traverson:

import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.client.Traverson;

Traverson traverson;
try{
    traverson = new Traverson(new URI("http://localhost:8080/context"), MediaTypes.HAL_JSON);
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("code", "foo");

    MyObjects myObjects = traverson.follow("my-objects", "search", "findByCode").withTemplateParameters(
                parameters).toObject(MyObjects.class);
} catch (URISyntaxException e) {}

If you don't want to extend your POJO MyObject with ResourceSupport class, your Resources class should be typed with Resource:

import org.springframework.hateoas.Resource;
import org.springframework.hateoas.Resources;

public class MyObjects extends Resources<Resource<MyObject>> { }

(If you don't need links the type parameter may again be MyObject).

Upvotes: 5

Related Questions