diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cf6a31c --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.idea +out +alura-stickers.iml \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..e69de29 diff --git a/src/JsonParser.java b/src/JsonParser.java new file mode 100644 index 0000000..f7dd6b4 --- /dev/null +++ b/src/JsonParser.java @@ -0,0 +1,42 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class JsonParser { + + private static final Pattern REGEX_ITEMS = Pattern.compile(".*\\[(.+)\\].*"); + private static final Pattern REGEX_ATRIBUTOS_JSON = Pattern.compile("\"(.+?)\":\"(.*?)\""); + + public List> parse(String json) { + + Matcher matcher = REGEX_ITEMS.matcher(json); + if (!matcher.find()) { + + throw new IllegalArgumentException("Não encontrou items."); + } + + String[] items = matcher.group(1).split("\\},\\{"); + + List> dados = new ArrayList<>(); + + for (String item : items) { + + Map atributosItem = new HashMap<>(); + + Matcher matcherAtributosJson = REGEX_ATRIBUTOS_JSON.matcher(item); + while (matcherAtributosJson.find()) { + String atributo = matcherAtributosJson.group(1); + String valor = matcherAtributosJson.group(2); + atributosItem.put(atributo, valor); + } + + dados.add(atributosItem); + } + + return dados; + + } +} \ No newline at end of file diff --git a/src/Main.java b/src/Main.java new file mode 100644 index 0000000..1293f74 --- /dev/null +++ b/src/Main.java @@ -0,0 +1,38 @@ +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.HttpResponse.BodyHandlers; +import java.util.List; +import java.util.Map; + +public class Main { + public static void main(String[] args) throws IOException, InterruptedException { + + // fazer a requisição HTTP com o metodo GET dos top 250 filmes de acordo com o site imdb. + + String url = "https://mocki.io/v1/9a7c1ca9-29b4-4eb3-8306-1adb9d159060"; + URI endereco = URI.create(url); + HttpClient httpClient = HttpClient.newHttpClient(); + HttpRequest request = HttpRequest.newBuilder(endereco).GET().build(); + HttpResponse response = httpClient.send(request, BodyHandlers.ofString()); + String body = response.body(); + + // extrair os dados que interessam (titulo, poster, classificação) + + JsonParser jsonParser = new JsonParser(); + List> listaDeFilmes = jsonParser.parse(body); + + // manipular e exibir os dados + + for (Map filme : listaDeFilmes) { + System.out.println(filme.get("title")); + System.out.println(filme.get("imDbRating")); + System.out.println(filme.get("image")); + System.out.println(); + } + + + } +} \ No newline at end of file