previous lesson > 2022.02.05 - [JAVA] - [java] java network, 특정 URL로부터 정보를 얻어오는 방법 1 - 접근/읽어오기
Reference lesson > 2022.02.06 - [JAVA] - [java] java network, URL로부터 얻은 정보 합치기 - StringBuilder
# json Library
org.json.jar
0.05MB
<How to get information from a specific URL in java 2 - jsonText to [JSONArray or jSONObject]>
- 1단계 > StringBuilder를 사용해서 데이터 값을 모아보자.
- 2단계 > JSONArray / JSONObeject 를 사용하여 구축한 network에서 가져온 데이터를 속성에 맞게 추출해보자.
>> 문자열을 배열을 가진 객체로 만들어주는 매커니즘(jsonText >> [JSONArray or jSONObject])을 위해 파싱 라이브러리(org.json.jar - JSONparse) 사용
1. 해당 URL의 정보를 처리할 수 있는 서버
>> 프로젝트명 : jsp08rest (다이나믹웹프로젝트)
>> 경로 : http://localhost:8090/jsp08rest (로컬)
>> 서버 쪽 코드 : 2022.02.06 - [분류 전체보기] - [java] jsp, json 웹페이지에 데이터 값 띄우기 2 - JSONArray / JSONObject 으로 배열 값 객체화
#코드
package test.com;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class test01Main2 {
public static void main(String[] args) {
System.out.println("network...");
String path = "http://localhost:8090/jsp08rest/json_selectAll.do";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
System.out.println(conn.getResponseCode());//연결 상태 확인
System.out.println(conn.getContentType());//데이타 타입 확인
if (conn.getResponseCode() == 200) {
BufferedReader br = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
//가져온 정보(readLine)값이 있다면 값을 받아서, StringBuilder로 값을 모아줘
StringBuilder jsonText = new StringBuilder();
String str = "";
while ((str = br.readLine()) != null) {
jsonText.append(str);
}
System.out.println(jsonText.toString());//모은 데이터 출력해줘(확인용)
//jsonText >> [JSONArray or jSONObject] >> 배열 데이터 객체화
System.out.println("====org.json.jar==========");
try {
JSONArray arr = new JSONArray(jsonText.toString());
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
System.out.println(obj.get("num"));
System.out.println(obj.get("name"));
System.out.println(obj.get("age"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}//end if
} catch (MalformedURLException e) {
System.out.println("MalformedURLException...");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOException...");
e.printStackTrace();
}
System.out.println("end Main...");
}// end main()
}
#결과값
1. 데이터가 한 개의 문자열로 합쳐 진것을 확인 할 수 있다.
2. 데이터가 객체화 되어 속성별로 분리되어 출력 가능한 것을 볼 수 있다.
'JAVA(STS)' 카테고리의 다른 글
[java] jdbc로 CRUD 기능을 수행하는 MVC(model 2) 뼈대 만들기 - DB통신 파트 예제1 (0) | 2022.02.07 |
---|---|
[java] jsp, json 웹페이지에 데이터 값 띄우기 2 - JSONArray / JSONObject 으로 배열 값 객체화 (0) | 2022.02.06 |
[java] java network, URL로부터 얻은 정보 합치기 - StringBuilder (0) | 2022.02.06 |
[java] SPS(spring tool suite)에서 프로젝트에 라이브러리 추가하기 (0) | 2022.02.05 |
[java] 대용량 문자열 처리 객체 StringBuilder() (대용량 문자열 합체시 유용한 객체)와 복합 연산자 "+=" 속도 비교 (0) | 2022.02.05 |