Ya estoy inscrito ¿Todavía no tienes acceso? Nuestros Planes
Ya estoy inscrito ¿Todavía no tienes acceso? Nuestros Planes
1
respuesta

[Proyecto] Mi propuesta de solución con Gson y Jackson...

public class PrincipalConBusqueda {
    public static void main(String[] args) {
        var moviesWithJacksonAndGson = new HashMap<String, List<Titulo>>();
        moviesWithJacksonAndGson = findMovies();
        writeMoviesAsJson(moviesWithJacksonAndGson);
        System.out.println("Finaliza la ejecución del programa... ¡Gracias!");
    }

    private static HashMap<String, List<Titulo>> findMovies() {
        var allMovies = new HashMap<String, List<Titulo>>();
        List<Titulo> moviesJackson = new ArrayList<>();
        List<Titulo> moviesGson = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.print("Escriba el nombre de una pelicula o salir: ");
            var movieName = scanner.nextLine();

            if (movieName.equals("salir")) break;

            try {
                String jsonBody = Omdb.getMovieByName(movieName);
                TituloOmdb omdbWithJackson = Mapper.toObjectWithJackson(jsonBody, TituloOmdb.class);
                TituloOmdb omdbWithGson = Mapper.toObjectWithGson(jsonBody, TituloOmdb.class);

                Titulo newTitleFromJackson = new Titulo(omdbWithJackson);
                Titulo newTitleFromGson = new Titulo(omdbWithGson);

                moviesJackson.add(newTitleFromJackson);
                moviesGson.add(newTitleFromGson);
            } catch (NumberFormatException e) {
                System.out.println("Ocurrió un error: ".concat(e.getLocalizedMessage()));
            } catch (IOException | InterruptedException e) {
                System.out.println("Algo salió mal en el servidor de OMDB, ".concat(e.getLocalizedMessage()));
            } catch (DurationConvertException e) {
                System.out.println(e.getLocalizedMessage());
            }
        }
        allMovies.put("WithJackson", moviesJackson);
        allMovies.put("WithGson", moviesGson);
        return allMovies;
    }

    private static void writeMoviesAsJson(HashMap<String, List<Titulo>> moviesWithJacksonAndGson) {
        var moviesJackson = moviesWithJacksonAndGson.get("WithJackson");
        var moviesGson = moviesWithJacksonAndGson.get("WithGson");

        BufferedWriter fileGson = ArchivoJson.createJsonFile("peliculasGson");
        ArchivoJson.escribir(fileGson, Mapper.toJsonWithGson(moviesGson));
        BufferedWriter fileJackson = ArchivoJson.createJsonFile("peliculasJackson");
        try {
            ArchivoJson.escribir(fileJackson, Mapper.toJsonWithJackson(moviesJackson));
        } catch (JsonProcessingException e) {
            System.out.println("Error al mappear con Jackson");
        }
    }
}
public class Mapper {
    private static final ObjectMapper mapperJackson = new ObjectMapper()
            .setPropertyNamingStrategy(PropertyNamingStrategies.UPPER_CAMEL_CASE);
    private static final Gson mapperGson = new GsonBuilder().setPrettyPrinting()
            .setFieldNamingStrategy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();

    public static <T> T toObjectWithJackson(String json, Class<T> tClass) throws JsonProcessingException {
        return mapperJackson.readValue(json, tClass);
    }

    public static String toJsonWithJackson(Object obj) throws JsonProcessingException {
        return mapperJackson.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
    }

    public static <T> T toObjectWithGson(String json, Class<T> tClass) {
        return mapperGson.fromJson(json, tClass);
    }

    public static String toJsonWithGson(Object obj) {
        return mapperGson.toJson(obj);
    }
}
public class ArchivoJson {

    public static BufferedWriter createJsonFile(String name) {
        try {
            return new BufferedWriter(new FileWriter(name.concat(".json")));
        } catch (IOException e) {
            throw new CreateJsonException("No se pudo crear el archivo json ".concat(name));
        }
    }

    public static void escribir(BufferedWriter file, String content) {
        try {
            file.write(content);
            file.close();
        } catch (IOException e) {
            throw new CreateJsonException("No se pudo escribir en el archivo json");
        }
    }
}
public class Omdb {
    private static final String API_KEY = "your apiKey";
    private static final String BASE_URI = "https://www.omdbapi.com/?apikey=".concat(API_KEY);
    private static final HttpClient client = HttpClient.newHttpClient();

    public static String getMovieByName(String movieName) throws IOException, InterruptedException {
        var uriStr = BASE_URI.concat("&t=").concat(URLEncoder.encode(movieName, StandardCharsets.UTF_8));
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create(uriStr)).build();
        return client.send(request, HttpResponse.BodyHandlers.ofString()).body();
    }
}
1 respuesta

¡Hola Wilmar! ¿Cómo estás?

Gracias por tu aporte en el foro. Tu contribución es esencial para el crecimiento de nuestra comunidad en Alura.

Sigue así y no dudes en volver al foro si tienes alguna pregunta o dificultad.

Abrazos y buenos estudios!

Si este post te ayudó, por favor, marca como solucionado ✓. Continúa con tus estudios!