Faça como eu fiz: consumindo uma API, criando classes e interfaces, e implementando métodos:
package br.com.alura.screenmatchsecond.service;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class ConsumoApi {
public String obterDados(String endereco) {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(endereco))
.build();
HttpResponse<String> response = null;
try {
response = client
.send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
String json = response.body();
return json;
}
}
package br.com.alura.screenmatchsecond.model;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public record DadosSerie(@JsonAlias("Title") String titulo,
@JsonAlias("totalSeasons") Integer totalTemporadas,
@JsonAlias("imdbRating") String avaliacao) {
}
package br.com.alura.screenmatchsecond.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ConverteDados implements IConverteDados {
private ObjectMapper mapper = new ObjectMapper();
@Override
public <T> T obterDados(String json, Class<T> classe) {
try {
return mapper.readValue(json, classe);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}
package br.com.alura.screenmatchsecond.service;
public interface IConverteDados {
<T> T obterDados(String json, Class<T> classe);
}
package br.com.alura.screenmatchsecond;
import br.com.alura.screenmatchsecond.model.DadosSerie;
import br.com.alura.screenmatchsecond.service.ConsumoApi;
import br.com.alura.screenmatchsecond.service.ConverteDados;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ScreenmatchsecondApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(ScreenmatchsecondApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
var consumoApi = new ConsumoApi();
var json = consumoApi.obterDados("http://www.omdbapi.com/?t=gilmore+girls&apikey=2669****");
System.out.println("\n");
System.out.println(json);
ConverteDados conversor = new ConverteDados();
DadosSerie dados = conversor.obterDados(json, DadosSerie.class);
System.out.println("\n");
System.out.println(dados);
}
}