O meu acabou ficando bem diferente do sugerido pela professora, fiz sem guardar os CEPs em um Record. Comentários e críticas são bem-vindos!
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String mensagemMenu = """
%%%%%%%%%%%%%%%%%%%% Checador de CEP %%%%%%%%%%%%%%%%%%%
Digite o cep para checar o endereço ou digite 'exit' para sair:""";
String cep = "0";
while (true) {
try {
PesquisadorDeCep pesquisadorDeCep = new PesquisadorDeCep();
GeradorDeJson geradorDeJson = new GeradorDeJson();
System.out.println(mensagemMenu);
cep = scanner.nextLine();
if (cep.equalsIgnoreCase("exit")) {
break;
}
String cepPretty = pesquisadorDeCep.pesquisarCep(cep);
System.out.println("Aqui está o CEP:");
System.out.println(cepPretty);
geradorDeJson.gerarArquivoJson(cepPretty);
System.out.println("Arquivo Gerado.");
System.out.println(" ");
} catch (JsonSyntaxException e){
System.out.println("Cep Inválido");
}
}
}
}
public class PesquisadorDeCep {
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
CriadorDeRequest request = new CriadorDeRequest();
String pesquisarCep(String cep) {
String url = "https://viacep.com.br/ws/" + cep + "/json/";
String json = request.criarRequest(url);
Map<String, Object> cepMapeado = gson.fromJson(json, Map.class);
String cepBonito = gson.toJson(cepMapeado);
return cepBonito;
}
}
public class GeradorDeJson {
public void gerarArquivoJson(String string){
try {
FileWriter listaJson = new FileWriter("cep.json");
listaJson.write(string);
listaJson.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public class CriadorDeRequest {
public String criarRequest(String url){
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.build();
HttpResponse<String> response = client
.send(request, HttpResponse.BodyHandlers.ofString());
return response.body();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}