Search code examples
javaspringspring-bootspring-mvcresttemplate

Consuming RestTemplate API response


I need same help. I have the POJO class, I need to consume the starwar API, take the result and transform it into objects.

@JsonIgnoreProperties(ignoreUnknown = true)
public class Planeta {

private String name;
private String climate; 
private String terrain;



 Getters and Setters...

Application.java

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());
    };
}
}

for some reason I'm getting null values.

The url api result is

{"data":[{"id":"5c378401c0ac520ffc670019","name":"terra","climate":"tropical","terrain":"earth"}],"erros":null}

logs

Application : Planeta [name=null, climate=null, terrain=null]

edited;


Solution

  • The JSON response doesn't match to you POJO, response is JSONObject with JsonArray (key = "data") and array consists of Planeta objects

    @JsonIgnoreProperties(ignoreUnknown = true)
    public class Response{
    
     @JsonProperty("data")
     List<Planeta> data;
    
     }
    

    If you have only one Planeta object in List,

    Planeta p = data.stream().findFirst().get();
    System.out.println(p.getName());
    

    If you have multiple objects in List

    for each

    for(Planeta p :data) {
            System.out.println(p.getName());
            // same for climate and terrain
        }
    

    java-8

    data.forEach(planeta-> System.out.println(planeta.getName()));