Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.