-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathReadTodosEx.java
70 lines (51 loc) · 1.76 KB
/
ReadTodosEx.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.zetcode;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
class Todo {
private int userId;
private int id;
@Expose
private String title;
private boolean completed;
public Todo(int userId, int id, String title, boolean completed) {
this.userId = userId;
this.id = id;
this.title = title;
this.completed = completed;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Todo{");
sb.append("userId=").append(userId);
sb.append(", id=").append(id);
sb.append(", title='").append(title).append('\'');
sb.append(", completed=").append(completed);
sb.append('}');
return sb.toString();
}
}
public class ReadTodosEx {
public static void main(String[] args) throws IOException, InterruptedException {
String url = "https://jsonplaceholder.typicode.com/todos";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
var jsonString = response.body();
System.out.println(jsonString);
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.setPrettyPrinting()
.create();
Todo[] todos = gson.fromJson(jsonString, Todo[].class);
gson.toJson(todos, System.out);
}
}