2016-10-12 52 views
0

我正在使用REST API公开的spring-data-rest应用程序。我正在使用此API来构建Web应用程序。但我无法将此API响应转换为POJO以便于使用。我有如下如何使用RestTEmplate映射spring-data-rest JSON响应及其对象

{ 
    "_links" : { 
    "self" : { 
     "href" : "http://localhost:8080/persons{&sort,page,size}", 
     "templated" : true 
    }, 
    "next" : { 
     "href" : "http://localhost:8080/persons?page=1&size=5{&sort}", 
     "templated" : true 
    } 
    }, 
    "_embedded" : { 
    "person": { 
     "id": 1, 
     "name": "John" 
    } 
    }, 
    "page" : { 
    "size" : 5, 
    "totalElements" : 50, 
    "totalPages" : 10, 
    "number" : 0 
    } 
} 

restTemplate.getForObject(uri, Person.class); 

这restTemplate抛出我下面的错误

22:50:10.377 [http-bio-8080-exec-28] DEBUG c.o.x.o.accessor.XWorkMethodAccessor - Error calling method through OGNL: object: [[email protected]] method: [viewPersons] args: [[]] 
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized field "_embedded" (Class com.foo.support.model.Person), not marked as ignorable 
at [Source: [email protected]f35; line: 2, column: 18] (through reference chain: com.foo.support.model.Person["_embedded"]); nested exception is org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "_embedded" (Class com.foo.support.model.Person), not marked as ignorable 
at [Source: [email protected]f35; line: 2, column: 18] (through reference chain: com.foo.support.model.Person["_embedded"]) 
     at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:127) ~[spring-web-3.1.0.RELEASE.jar:3.1.0.RELEASE] 
     at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:153) ~[spring-web-3.1.0.RELEASE.jar:3.1.0.RELEASE] 
     at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:81) ~[spring-web-3.1.0.RELEASE.jar:3.1.0.RELEASE] 
     at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:446) ~[spring-web-3.1.0.RELEASE.jar:3.1.0.RELEASE] 
     at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:401) ~[spring-web-3.1.0.RELEASE.jar:3.1.0.RELEASE] 
     at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:199) ~[spring-web-3.1.0.RELEASE.jar:3.1.0.RELEASE] 

Person.java响应

public class Person { 
    private int id; 
    private String name; 

    // getters and setters 
} 

如何从响应Person对象?我不想在我的Persion类中包含_embedded字段。

回答

2

其余响应的返回类型不是Person.class - 它是PagedResources<Person>

为了使用RestTemplate与泛型类型,你可以使用以下命令:

PagedResources<Person> = restTemplate.exchange(
        uri, 
        HttpMethod.GET, 
        null, 
        new ParametrizedReturnType()).getBody(); 

private static final class ParametrizedReturnType extends TypeReferences.PagedResourcesType<Person> {} 
+0

谢谢您的回答。但我的PagedResource类型是动态的。那可能是个人或员工或访客。我不想为所有这些申报单独的课程。因为响应可能是PagedResource 或资源 SST