Screenmatch1Application.java
package com.valentina.screenmatch1;
import com.valentina.screenmatch1.model.DatosSerie;
import com.valentina.screenmatch1.service.ConsumoAPI;
import com.valentina.screenmatch1.service.ConvierteDatos;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Screenmatch1Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Screenmatch1Application.class, args);
}
@Override
public void run(String... args) throws Exception {
var consumoApi = new ConsumoAPI();
var json = consumoApi.obtenerDatos("https://www.omdbapi.com/?t=the+100&apikey=b38d6b01");
System.out.println(json);
ConvierteDatos conversor = new ConvierteDatos();
var datos = conversor.obtenerDatos(json, DatosSerie.class);
System.out.println(datos);
}
}
DatosSerie.java
package com.valentina.screenmatch1.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) {
}
ConvierteDatos.java
package com.valentina.screenmatch1.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.valentina.screenmatch1.model.DatosSerie;
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);
}
}
}
IConvierteDatos.Java
package com.valentina.screenmatch1.service;
public interface IConvierteDatos {
<T> T obtenerDatos(String json, Class<T> clase);
}
ConsumoAPI.java
package com.valentina.screenmatch1.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;
}
}