[英]Consuming RestTemplate API response
我需要同樣的幫助。 我有POJO類,我需要使用starwar API,獲取結果並將其轉換為對象。
@JsonIgnoreProperties(ignoreUnknown = true)
public class Planeta {
private String name;
private String climate;
private String terrain;
Getters and Setters...
應用程序
package hello;
@SpringBootApplication
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String args[]) {
SpringApplication.run(Application.class);
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
Planeta planeta = restTemplate.getForObject("http://localhost:8080/planeta/name/terra", Planeta.class);
log.info(planeta.getName());
};
}
}
由於某種原因,我得到了空值。
網址api結果是
{"data":[{"id":"5c378401c0ac520ffc670019","name":"terra","climate":"tropical","terrain":"earth"}],"erros":null}
日志
Application : Planeta [name=null, climate=null, terrain=null]
編輯;
JSON響應與您的POJO不匹配,響應是帶有JsonArray
(鍵=“數據”)的JSONObject
,並且數組由Planeta
對象組成
@JsonIgnoreProperties(ignoreUnknown = true)
public class Response{
@JsonProperty("data")
List<Planeta> data;
}
如果List
只有一個Planeta
對象,
Planeta p = data.stream().findFirst().get();
System.out.println(p.getName());
如果List
有多個對象
每個
for(Planeta p :data) {
System.out.println(p.getName());
// same for climate and terrain
}
Java-8
data.forEach(planeta-> System.out.println(planeta.getName()));
API返回的是一個具有關鍵data
的對象,在該對象內部有一系列行星,而不是一個。 您只需要一個,就沒有數據字段。 JSON與您預期的Planeta類不匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.