파싱 : 구문 분석, 이해
데이터를 보낼 때 문제점
- 데이터를 보내면 오브젝트가 문자열로 바뀌어서 전송되기 때문에 다시 오브젝트로 변환시켜야한다.(버퍼는 Byte Stream)
- 통신은 모두 문자열
- 서로 다른 언어로 만들어진 프로그램이 통신을 할 때 문자열을 어떻게 오브젝트로 변환시켜도 (컴퓨터가) 그 오브젝트를 이해할 수 없다.(모든 언어는 자기 만의 문법을 가지고있다.)
- 50. JSON 참고
라이브러리 설치
파싱에 필요한 jackson 라이브러리

파싱할 데이터 URL
Post class
public class Post {
private int userId;
private int id;
private String title;
private String body;
public Post() {}
public int getUserId() {
return userId;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
}
MyApp2 class
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MyApp2 {
public static void main(String[] args) {
try {
URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream())
);
String download = "";
while(true){
String line = br.readLine();
if(line == null) break;
download = download + line;
}
// System.out.println(download);
ObjectMapper om = new ObjectMapper();
Post post = om.readValue(download, Post.class);
System.out.println(post.getTitle());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

Share article