Skip to content

Instantly share code, notes, and snippets.

@cosminpopescu14
Last active July 5, 2020 06:38
Show Gist options
  • Save cosminpopescu14/4d6d43e2f9eaa1d4d9221b021d553d4a to your computer and use it in GitHub Desktop.
Save cosminpopescu14/4d6d43e2f9eaa1d4d9221b021d553d4a to your computer and use it in GitHub Desktop.
package com.company;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
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.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
// write your code here
String DATA_URL = "https://jsonplaceholder.typicode.com/todos";
var httpClient = HttpClient.newHttpClient();
var httpRequest = HttpRequest.newBuilder()
.uri(URI.create(DATA_URL))
.build();
var httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
var body = httpResponse.body();
var mapper = new ObjectMapper();
Todo[] todos = mapper.readValue(body, Todo[].class); //because in json representation in an array of todos
//System.out.println(todos[1].title());
var doneTodos = Arrays.stream(todos)
.filter(Todo::completed)
.count();
System.out.println("Completed: " + doneTodos);
System.out.println("Not completed: " + (todos.length - doneTodos));
}
}
//https://angiejones.tech/deserializing-api-responses-into-java-records
record Todo(
@JsonProperty("userId")
int userId,
@JsonProperty("id")
int id,
@JsonProperty("title")
String title,
@JsonProperty("completed")
boolean completed) {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment