json형식의 데이터를 받는 방법, 받아서 java spring안에서 다루는 방법에 대해 정리하려 한다. 공공데이터사이트에 프로그래밍 언어별로 데이터를 읽어 출력하는 샘플코드가 있다.
public class ApiExplorer {
public static void main(String[] args) throws IOException {
StringBuilder urlBuilder = new StringBuilder("http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19InfStateJson"); /*URL*/
urlBuilder.append("?" + URLEncoder.encode("serviceKey","UTF-8") + "=서비스키"); /*Service Key*/
urlBuilder.append("&" + URLEncoder.encode("pageNo","UTF-8") + "=" + URLEncoder.encode("1", "UTF-8")); /*페이지번호*/
urlBuilder.append("&" + URLEncoder.encode("numOfRows","UTF-8") + "=" + URLEncoder.encode("10", "UTF-8")); /*한 페이지 결과 수*/
urlBuilder.append("&" + URLEncoder.encode("startCreateDt","UTF-8") + "=" + URLEncoder.encode("20200310", "UTF-8")); /*검색할 생성일 범위의 시작*/
urlBuilder.append("&" + URLEncoder.encode("endCreateDt","UTF-8") + "=" + URLEncoder.encode("20200315", "UTF-8")); /*검색할 생성일 범위의 종료*/
URL url = new URL(urlBuilder.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) {
sb.append(line);
}
rd.close();
conn.disconnect();
System.out.println(sb.toString());
}
보통 urlBuilder나 java.net.url을 이용해 주소를 저장하고 BufferReader 에서 주소를 읽어오는 방식인 것 같다.
+참고:
다른 몇 분의 방식을 살펴보니 json.simple 라이브러리를 이용해 parser에서 parse해오고 json데이터의 구조에 따라 순차적으로 get해오는 방식이 틀리진 않은 것 같다. jsonobject의 배열의 경우 arr.get()에서 index를 인자로 받아올 수 있다.
나의 경우에는 아래와 같이 json.simple을 이용했다.
try {
String requestDate=date;
URL url = new URL("http://openapi.seoul.go.kr:8088/" + "인증키/" +
"json/CardSubwayStatsNew/1/700/"+requestDate);
BufferedReader bf;
bf = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
result = bf.readLine();
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(result);
JSONObject CardSubwayStatsNew = (JSONObject)jsonObject.get("CardSubwayStatsNew");
Long totalCount=(Long)CardSubwayStatsNew.get("list_total_count");
JSONObject subResult = (JSONObject)CardSubwayStatsNew.get("RESULT");
JSONArray infoArr = (JSONArray) CardSubwayStatsNew.get("row");
for(int i=0;i<infoArr.size();i++){
JSONObject tmp = (JSONObject)infoArr.get(i);
SubstationInfo infoObj=new SubstationInfo(i+(long)1, (String)tmp.get("USE_DT"),(String)tmp.get("LINE_NUM"),(String)tmp.get("SUB_STA_NM"),
(double)tmp.get("RIDE_PASGR_NUM"), (double)tmp.get("ALIGHT_PASGR_NUM"),(String)tmp.get("WORK_DT"));
infoRepository.save(infoObj);
}
}catch(Exception e) {
e.printStackTrace();
}
java.net.url이나 parse()는 exception은 throw하므로 이를 사용할 떄 try{}catch{}로 감싸주지 않으면 unhandledException 컴파일 에러가 난다.
json.simple 이외에도 gson이나 jackson같은 json관련 라이브러리들이 있다. 필요에 따라 선택해서 사용하면 되겠다.