【发布时间】:2021-08-10 10:34:12
【问题描述】:
我正在使用swapi.dev API 将数据获取到我在 Spring Boot 中的应用程序。我需要使用其名称获取有关行星的信息。因此,我使用下一个网址:https://swapi.dev/api/planets/?search=Tatooine。 JSON 结果如下:
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"name": "Tatooine",
"rotation_period": "23",
"orbital_period": "304",
"diameter": "10465",
"climate": "arid",
"gravity": "1 standard",
"terrain": "desert",
"surface_water": "1",
"population": "200000",
"residents": [
"http://swapi.dev/api/people/1/",
"http://swapi.dev/api/people/2/",
"http://swapi.dev/api/people/4/",
"http://swapi.dev/api/people/6/",
"http://swapi.dev/api/people/7/",
"http://swapi.dev/api/people/8/",
"http://swapi.dev/api/people/9/",
"http://swapi.dev/api/people/11/",
"http://swapi.dev/api/people/43/",
"http://swapi.dev/api/people/62/"
],
"films": [
"http://swapi.dev/api/films/1/",
"http://swapi.dev/api/films/3/",
"http://swapi.dev/api/films/4/",
"http://swapi.dev/api/films/5/",
"http://swapi.dev/api/films/6/"
],
"created": "2014-12-09T13:50:49.641000Z",
"edited": "2014-12-20T20:58:18.411000Z",
"url": "http://swapi.dev/api/planets/1/"
}
]
}
现在,在 Java 中,我使用服务中的下一个代码:
public PlanetDTO getPlanetByName(String name){
String url = "https://swapi.dev/api/planets/?search=Tatooine";
RestTemplate restTemplate = new RestTemplate();
Object object = restTemplate.getForObject(url, Object.class);
// I don't know how to get the array of results
}
我只需要获取结果数组,但是,如何从对象中获取结果数组?
【问题讨论】:
-
如果我没记错的话,你唯一需要做的就是在课堂上指出,你要映射,它不是一个单一的,它是一个数组。您可以使用对象 来实现。如果您需要列表,则使用 ParameterizedTypeReference 类或类。它会类似于 ....(getForObject(url, new ParameterizedTypeReference
- ())
-
但是 url 返回一个 JSON 对象。我想要得到的是该对象@AL 的数组
标签: java spring-boot rest resttemplate