我正在使用Spring在Spring中将数据获取到我的应用程序。我需要用它的名字来获取行星上的信息。因此,我使用下一个url: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
}
我只需要得到结果数组,但是,,如何从对象获得结果数组?
发布于 2021-05-21 01:22:29
由于您使用的是Spring,所以它通常与方便的JSON解析工具捆绑在一起。Spring连接每个默认的jackson到您的应用程序中。
首先,您需要的是响应的(约简) POJO模型。
@JsonIgnoreProperties(ignoreUnknown = true)
public class ResponsePojo {
@JsonProperty("<jsonFieldName>") // only required, if fieldName != jsonFieldName
private List<String> residents;
/* getter & setter ommitted */
}
在调用代码中,使用以下内容
ResponsePojo response = restTemplate.getForObject(url, ResponsePojo.class);
response.getResidents() gives you access to the contents of 'resident' array
幕后发生了什么?
RestTemplate发送请求并尝试将响应解析到ResponsePojo对象中。由于pojo是响应的简化表示,所以我们提供了注释@JsonIgnoreProperties(ignoreUnknown = true)
。这告诉解析器,它应该简单地忽略json中无法映射到您的pojo的任何字段。由于提供了类似于json的字段,解析器能够相应地识别和映射它们。
https://stackoverflow.com/questions/67632793
复制相似问题