package br.com.alura.screenmatch.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.screenmatch.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.screenmatch.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.screenmatch.service;
public interface IConverteDados {
<T> T obterDados(String json, Class<T> classe);
}
package br.com.alura.screenmatch;
import br.com.alura.screenmatch.model.DadosSerie;
import br.com.alura.screenmatch.service.ConsumoApi;
import br.com.alura.screenmatch.service.ConverteDados;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ScreenmatchApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(ScreenmatchApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
ConsumoApi consumoApi = new ConsumoApi();
var json = consumoApi.obterDados("https://www.omdbapi.com/?t=gilmore+girls&apikey=6585022c");
System.out.println(json);
ConverteDados conversor = new ConverteDados();
DadosSerie dados = conversor.obterDados(json, DadosSerie.class);
System.out.println(dados);
}
}
O código está disponível no GitHub para consulta: https://github.com/harlenregis/screenmatch-sem-web.git