package com.aluracursos.screenmatch;
import com.aluracursos.screenmatch.model.DatosSerie;
import com.aluracursos.screenmatch.service.ConsumoAPI;
import com.aluracursos.screenmatch.service.ConvierteDatos;
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 {
var consumoApi = new ConsumoAPI();
var json = consumoApi.obtenerDatos("https://www.omdbapi.com/?t=game-of+thrones&apikey=c236e1a");
//var json = consumoApi.obtenerDatos("https://coffee.alexflipnote.dev/random.json");
System.out.println(json);
ConvierteDatos conversor = new ConvierteDatos();
var datos = conversor.obtenerDatos(json, DatosSerie.class);
System.out.println(datos);
}
}
package com.aluracursos.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 obtenerDatos(String url){
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.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 com.aluracursos.screenmatch.service;
public interface IConvierteDatos {
<T> T obtenerDatos(String json, Class<T> clase);
}
package com.aluracursos.screenmatch.service;
import com.aluracursos.screenmatch.model.DatosSerie;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ConvierteDatos implements IConvierteDatos {
private ObjectMapper objectMapper = new ObjectMapper();
@Override
public <T> T obtenerDatos(String json, Class<T> clase) {
try {
return objectMapper.readValue(json, clase);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}
package com.aluracursos.screenmatch.model;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public record DatosSerie(
@JsonAlias("Title") String titulo,
@JsonAlias("totalSeasons") Integer totalDeTemporadas,
@JsonAlias("imdbRating") String evaluacion) {
}