메서드
package com.mtcoding.ex11;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
// 책임 : 저장소(다른 사람 서버, HDD, DB)에서 데이터 가져오기
public class Repository {
// 책임 : 통신에서 다운로드하는 책임
public String download(String site) throws Exception {
// 1. 소켓 연결 완료
URL url = new URL(site);
HttpURLConnection socket = (HttpURLConnection) url.openConnection();
// 2. 읽기 버퍼 연결
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream())
);
// 3. 다운로드
String json = "";
while (true) {
String line = br.readLine(); // 값이 없으면 null을 준다.
if (line == null) break;
json = json + line; // if를 위에 안하면 {}null이 붙어서 파싱이 제대로 안 될 수도 있음
}
return json;
}
}PostApp (Post 클래스 + PostApp-main)
package com.mtcoding.ex11;
import com.google.gson.Gson;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
class Post {
private Integer userId;
private Integer id;
private String title;
private String body;
}
// GSON 라이브러리 작동 방법
// 1. Post 객체를 new 한다 -> "디폴트 생성자"를 new 한다.
// 2. Post 객체에 setter를 호출한다.
public class PostApp {
public static void main(String[] args) {
String json = """
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto"
}
""";
Gson gson = new Gson();
Post p = gson.fromJson(json, Post.class); // Post.class 는 클래스의 위치와 클래스명 알려줌
System.out.println();
}
}

PostNetworkApp (main)
package com.mtcoding.ex11;
import com.google.gson.Gson;
public class PostNetworkApp {
public static void main(String[] args) {
try {
Repository repo = new Repository();
String json = repo.download("https://jsonplaceholder.typicode.com/posts/1");
Gson gson = new Gson();
Post p = gson.fromJson(json, Post.class);
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Share article