풀스택개발자_대학교 정규과정/프로젝트_throwsgg
open API 파싱하기(JSON)
- -
API란, Application Programming Interface의 약자로, 응용 프로그램에서 사용할 수 있도록, 운영 체제나 프로그래밍 언어가 제공하는 기능을 제어할 수 있게 만든 인터페이스를 뜻한다.
OPEN API란, 사용자가 제공되는 데이터를 자유롭게 활용할 수 있도록 만들어놓은 인터페이스이다.
우리나라는 공공데이터 포털에서 각종 데이터들을 API형태로 제공해주고 있는데, 그 밖에 다양한 사이트에서도 제공해준다.
API로 제공되어지는 형태는 대부분 JSON이나 XML로 제공된다.
※ HttpURLConnection 객체 생성해서 url 연결하기
StringBuilder urlBuilder = new StringBuilder( "http://apis.data.go.kr/1543061/abandonmentPublicSrvc/abandonmentPublic"); /* URL */ urlBuilder.append("?" + URLEncoder.encode("serviceKey", "UTF-8") + "서비스키"); /* * Service * Key */ urlBuilder.append("&" + URLEncoder.encode("numOfRows", "UTF-8") + "=" + URLEncoder.encode("6", "UTF-8")); /* 한 페이지 결과 수(1,000 이하) */ urlBuilder.append( "&" + URLEncoder.encode("pageNo", "UTF-8") + "=" + URLEncoder.encode(pageNum, "UTF-8")); /* 페이지 번호 */ urlBuilder.append("&" + URLEncoder.encode("_type", "UTF-8") + "=" + URLEncoder.encode("json", "UTF-8")); /* xml(기본값) 또는 json */ URL url = new URL(urlBuilder.toString()); // System.out.println(url.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-type", "application/json"); // System.out.println("Response code: " + conn.getResponseCode()); BufferedReader rd; if (conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) { rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); } else { rd = new BufferedReader(new InputStreamReader(conn.getErrorStream())); } StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { System.out.println(line); sb.append(line); } rd.close(); conn.disconnect(); return sb.toString();
먼저 JSONParser를 사용해서 String 값을 JSON 객체로 만들어준다.
이 때, 만들어진 JSON 객체는 JSONObject 클래스를 사용해서 저장된다.
만들어진 JSONObject에서 최종적으로 key가 item 인 value를 추출하기 위해서 get() 을 사용한다.
{ "response" : { "header" : { "reqNo" : 35362175, "resultCode" : "00", "resultMsg" : "NORMAL SERVICE." }, "body" : { "items" : { "item" : [ { "desertionNo" : "469569202200522", "filename" : "http://www.animal.go.kr/files/shelter/2022/09/202209012009963_s.jpg", "happenDt" : "20220901", "happenPlace" : "부강면 갈산산수로 237-9 일대", "kindCd" : "[개] 진도견", "colorCd" : "흰색", "age" : "2015(년생)", "weight" : "12(Kg)", "noticeNo" : "세종-세종-2022-00292", "noticeSdt" : "20220901", "noticeEdt" : "20220913", "popfile" : "http://www.animal.go.kr/files/shelter/2022/09/202209012009963.jpg", "processState" : "보호중", "sexCd" : "F", "neuterYn" : "U", "specialMark" : "심장사상충 양성, 목줄 착용, 순함", "careNm" : "세종유기동물보호센터", "careTel" : "010-4435-3720", "careAddr" : "세종특별자치시 전동면 미륵당1길 188 (전동면) ", "orgNm" : "세종특별자치시", "chargeNm" : "동물복지담당", "officetel" : "044-300-7615" }, { "desertionNo" : "469569202200521", "filename" : "http://www.animal.go.kr/files/shelter/2022/09/202209012009324_s.jpg", "happenDt" : "20220901", "happenPlace" : "조치원읍 봉산1길 84", "kindCd" : "[개] 믹스견", "colorCd" : "흰색", "age" : "2021(년생)", "weight" : "4(Kg)", "noticeNo" : "세종-세종-2022-00291", "noticeSdt" : "20220901", "noticeEdt" : "20220913", "popfile" : "http://www.animal.go.kr/files/shelter/2022/09/202209012009324.jpg", "processState" : "보호중", "sexCd" : "F", "neuterYn" : "U", "specialMark" : "심장사상충 음성", "careNm" : "세종유기동물보호센터", "careTel" : "010-4435-3720", "careAddr" : "세종특별자치시 전동면 미륵당1길 188 (전동면) ", "orgNm" : "세종특별자치시", "chargeNm" : "동물복지담당", "officetel" : "044-300-7615" }, { "desertionNo" : "448546202200457", "filename" : "http://www.animal.go.kr/files/shelter/2022/08/202209011009710_s.jpg", "happenDt" : "20220901", "happenPlace" : "안의면", "kindCd" : "[개] 치와와", "colorCd" : "연한황토", "age" : "2017(년생)", "weight" : "4(Kg)", "noticeNo" : "경남-함양-2022-00163", "noticeSdt" : "20220901", "noticeEdt" : "20220913", "popfile" : "http://www.animal.go.kr/files/shelter/2022/08/202209011009710.jpeg", "processState" : "보호중", "sexCd" : "F", "neuterYn" : "N", "specialMark" : "치와와 종류, 약 5살정도, 약 4kg 정도, 온순함, 유기견", "careNm" : "함양군위탁보호소", "careTel" : "055-960-8143", "careAddr" : "경상남도 함양군 함양읍 함양남서로 996-76 (함양읍, 농업기술센터) ", "orgNm" : "경상남도 함양군", "officetel" : "055-960-8140" },
json 추출 코드
public static AbandonList getDataList(String pageNum) throws IOException, ParseException {
AbandonList list = new AbandonList(new ArrayList<DateAbandon>());
String result = ApiManagement.xmlDownload(pageNum);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(result);
JSONObject PetInfoResult = (JSONObject) jsonObject.get("response");
JSONObject PetInfoResult01 = (JSONObject) PetInfoResult.get("body");
JSONObject PetInfoResult02 = (JSONObject) PetInfoResult01.get("items");
JSONArray PetInfo = (JSONArray) PetInfoResult02.get("item");// item의 값은 여러개이기에 JSONArray 사용
String PetInfo_totalCount = String.valueOf(PetInfoResult01.get("totalCount"));
for (int i = 0; i < PetInfo.size(); i++) {
Gson gson = new Gson();
DateAbandon dateAbandon = gson.fromJson(PetInfo.get(i).toString(), DateAbandon.class);
list.getList().add(dateAbandon);
}
return list;
}
전체 코드
package gg;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import vo.AbandonList;
import vo.DateAbandon;
public class ApiManagement {
public static String xmlDownload(String pageNum) throws IOException {
StringBuilder urlBuilder = new StringBuilder(
"http://apis.data.go.kr/1543061/abandonmentPublicSrvc/abandonmentPublic"); /* URL */
urlBuilder.append("?" + URLEncoder.encode("serviceKey", "UTF-8")
+ "서비스키"); /*
* Service
* Key
*/
urlBuilder.append("&" + URLEncoder.encode("numOfRows", "UTF-8") + "="
+ URLEncoder.encode("6", "UTF-8")); /* 한 페이지 결과 수(1,000 이하) */
urlBuilder.append(
"&" + URLEncoder.encode("pageNo", "UTF-8") + "=" + URLEncoder.encode(pageNum, "UTF-8")); /* 페이지 번호 */
urlBuilder.append("&" + URLEncoder.encode("_type", "UTF-8") + "="
+ URLEncoder.encode("json", "UTF-8")); /* xml(기본값) 또는 json */
URL url = new URL(urlBuilder.toString());
// System.out.println(url.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-type", "application/json");
// System.out.println("Response code: " + conn.getResponseCode());
BufferedReader rd;
if (conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
public static AbandonList getDataList(String pageNum) throws IOException, ParseException {
AbandonList list = new AbandonList(new ArrayList<DateAbandon>());
String result = ApiManagement.xmlDownload(pageNum);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(result);
JSONObject PetInfoResult = (JSONObject) jsonObject.get("response");
JSONObject PetInfoResult01 = (JSONObject) PetInfoResult.get("body");
JSONObject PetInfoResult02 = (JSONObject) PetInfoResult01.get("items");
JSONArray PetInfo = (JSONArray) PetInfoResult02.get("item");// item의 값은 여러개이기에 JSONArray 사용
String PetInfo_totalCount = String.valueOf(PetInfoResult01.get("totalCount"));
for (int i = 0; i < PetInfo.size(); i++) {
Gson gson = new Gson();
DateAbandon dateAbandon = gson.fromJson(PetInfo.get(i).toString(), DateAbandon.class);
list.getList().add(dateAbandon);
}
return list;
}
}
Contents
소중한 공감 감사합니다