Java 如何使用SpringRESTTemplate获取JSON对象?
我正在使用API在Spring Boot中将数据获取到我的应用程序中。我需要用一个行星的名字来获取它的信息。因此,我使用下一个url:。JSON结果如下所示:Java 如何使用SpringRESTTemplate获取JSON对象?,java,spring-boot,rest,resttemplate,Java,Spring Boot,Rest,Resttemplate,我正在使用API在Spring Boot中将数据获取到我的应用程序中。我需要用一个行星的名字来获取它的信息。因此,我使用下一个url:。JSON结果如下所示: { "count": 1, "next": null, "previous": null, "results": [ { "name": "Tatooi
{
"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
}
我只需要获取结果数组,但是,如何从对象获取结果数组?由于您使用的是Spring Boot,因此它通常与用于JSON解析的便捷工具捆绑在一起。 Spring引导将默认jackson连接到应用程序中 首先,您需要一个(简化的)POJO响应模型
@JsonIgnoreProperties(ignoreUnknown = true)
public class ResponsePojo {
@JsonProperty("<jsonFieldName>") // only required, if fieldName != jsonFieldName
private List<String> residents;
/* getter & setter ommitted */
}
幕后发生了什么
RestTemplate发送您的请求,并尝试将响应解析为您的ResponsePojo对象。
由于pojo是响应的简化表示,因此我们提供了注释@JsonIgnoreProperties(ignoreUnknown=true)
。
这告诉解析器,它应该忽略json中无法映射到pojo的任何字段。由于提供了一个字段,其确切名称与json中的相同,因此解析器能够相应地识别和映射它们。如果我没有错,那么您唯一需要做的就是在类中指出,您要映射,它不是单个的,它是一个数组。你可以用Object来做。如果需要列表,请使用ParameteredTypeReference初始化或。它类似于……(getForObject,url,new ParameterizedTypeReferences,但url返回一个JSON对象。我想得到的是该对象的数组@ALYes。我使用POJO获得结果数组。感谢您的解释!!
ResponsePojo response = restTemplate.getForObject(url, ResponsePojo.class);
response.getResidents() gives you access to the contents of 'resident' array