我是Java领域的新手。我正在尝试使用Spring Data REST及其Android客户端构建REST服务。目前我正在尝试测试(JUnit)该服务。
当我致电服务获取用户列表(http://localhost:8080/..../api/users/)
时,我在Postman中收到以下回复{
"_embedded": {
"users": [{
"firstName" : "Maharaj",
"lastName" : "NaamChakrawarti",
"email" : "maharaj@mast.in.naam",
"_links" : {
"self" : {
"href" : "http://localhost:8080/.../api/users/2"
}
}
},{
"firstName" : "Ji",
"lastName" : "NaamChakrawartiDas",
"email" : "G@Naam.masti",
"_links" : {
"self" : {
"href" : "http://localhost:8080/.../api/users/3"
}
}
}]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/com.feiswrox.webserviceRS/api/users"
},
.
.
},
"page" : {
"size" : 20,
.
.
}
}
我尝试使用以下代码来解析此响应 -
private static HttpHeaders getHeaders() {
String plainCredentials = "G@Naam.masti:ShreeRam1974";
String base64Credentials = new String(Base64.encode(plainCredentials.getBytes()));
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Credentials);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
return headers;
}
@Test
// @SuppressWarnings("unchecked")
public void listAllUsersHal() {
System.out.println("\nTesting listAllUsersHal API-----------");
RestTemplate restTemplate = new RestTemplate();
HttpEntity<String> request = new HttpEntity<String>(getHeaders());
Collection<Resource<User>> userList = null;
ResponseEntity<Resources<Resource<User>>> responseResource = restTemplate.exchange(REST_SERVICE_URI + "/users/", HttpMethod.GET,
request, new ParameterizedTypeReference<Resources<Resource<User>>>() {}, Collections.emptyMap());
if (responseResource.getStatusCode() == HttpStatus.OK) {
System.out.println(responseResource.getBody().toString());
Resources<Resource<User>> userResource = responseResource.getBody();
userList = userResource.getContent();
for(Resource<User> userRsrc : userList){
System.out.println(userRsrc.toString());
}
}
}
我在userList变量中获得了一些值,但是代码执行会跳过循环 使用以下代码
ResponseEntity<String> responseString = restTemplate.exchange(REST_SERVICE_URI + "/users/", HttpMethod.GET,
request, String.class);
我得到一个与上面给出的字符串相同的字符串,即
{ "_embedded":{....
但我不知道如何将其解析为用户列表。
我使用类似的代码从json转换单个用户并且它起作用 RestTemplate restTemplate = new RestTemplate();
HttpEntity<String> request = new HttpEntity<String>(getHeaders());
ResponseEntity<Resource<User>> response = restTemplate.exchange(REST_SERVICE_URI + "/users/2", HttpMethod.GET,
request, new ParameterizedTypeReference<Resource<User>>() {});
User user = null;
if (response.getStatusCode() == HttpStatus.OK) {
Resource<User> userResource = response.getBody();
user = userResource.getContent();
}
我在输入以下代码时犯了什么错误吗?
Collection<Resource<User>> userList = null;
ResponseEntity<Resources<Resource<User>>> responseResource = restTemplate.exchange(REST_SERVICE_URI + "/users/", HttpMethod.GET,
request, new ParameterizedTypeReference<Resources<Resource<User>>>() {}, Collections.emptyMap());
请帮我构建REST服务返回的json用户列表。
我也可以在andriod应用程序中使用相同的代码吗?