Sto usando spring-data-rest per esporre le quadro come risorse di rest (paginate). Tutto funziona bene, ma quando richiedo i dati tramite RestTemplate
, ottengo un inutile JSON HATEOAS (che non ho chiesto). Il JSON sembra essere un PagedResources. Potrei vivere con quello, ma il JSON non viene convertito in un object correttamente. Non c’è content
all’interno.
repository:
@RepositoryRestResource(collectionResourceRel = "people", path = "people") public interface PersonRepository extends PagingAndSortingRepository { List findByLastName(@Param("name") String name); }
Cliente:
public List getPersons() { RestTemplate rt = new RestTemplate(); System.out.println(rt.getForObject(URL, PagedResources.class).getContent().size()); System.out.println(rt.getForObject(URL, PagedResources.class).getLinks().size()); System.out.println(rt.getForObject(URL, PagedResources.class).getMetadata().getTotalElements()); return new ArrayList(rt.getForObject(URL, PagedResources.class).getContent()); // <-- empty }
System.out:
0 // getContent().size() 4 // getLinks().size() 2 // getTotalElements()
arricciare:
C:\...>curl http://localhost:8080/spring-jsf-rest/rest/people { "_links" : { "self" : { "href" : "http://localhost:8080/spring-jsf-rest/rest/people{?page,size,sort}", "templated" : true }, "search" : { "href" : "http://localhost:8080/spring-jsf-rest/rest/people/search" } }, "_embedded" : { "people" : [ { "firstName" : "John", "lastName" : "Rambo", "_links" : { "self" : { "href" : "http://localhost:8080/spring-jsf-rest/rest/people/1" } } }, { "firstName" : "Chuck", "lastName" : "Norris", "_links" : { "self" : { "href" : "http://localhost:8080/spring-jsf-rest/rest/people/2" } } } ] }, "page" : { "size" : 20, "totalElements" : 2, "totalPages" : 1, "number" : 0 } }
Sembra che _embedded
non sia mappato correttamente al contenuto ?!
Come hai scoperto correttamente, PagedResources
non ha una proprietà _embedded
, ecco perché non ottieni la proprietà del content
popolata.
Questo dilemma può essere risolto in due modi diversi:
Fornire un tipo che corrisponde alla rappresentazione in primo luogo. Quindi, crea una class personalizzata e rispetta i nomi delle proprietà della rappresentazione o personalizzala usando le annotazioni di Jackson ecc.
Configura un MappingJackson2HttpMessageConverter
personalizzato e personalizza l’ ObjectMapper
per far sì che Jackson2HalModule
configuri in modo tale che Spring HATEOAS venga spedito fuori dalla scatola.
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.> singletonList(converter));