저번글에서는  json방식으로 api를 호출해서 데이터를 확인했다.

이번에는 api를 json으로 파싱을 해보려고 한다.

 

json관련 라이브러리 추가 방법과 파싱방법은 이전 게시글에 게시해놓았다.

2021.05.04 - [프로그래밍&IT/java] - [java 자바] JSON 파싱

 

[java 자바] JSON 파싱

JSON을 이용해 파싱을하려고 한다. 먼저 JSON을 사용하기 위해 JSON에 필요한 라이브러리(jar) 추가가 필요하다. 라이브러리 추가 방법은 두가지가 있다. 1. 직접 jar파일을 다운 받아서 추가 ohgbu88.tist

ohgbu88.tistory.com

 

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class apiTest {
    public static void main(String[] args)  throws IOException, ParseException {
        String serviceKey = "발급받은 서비스키값";
        String urlStr = "http://apis.data.go.kr/B552584/UlfptcaAlarmInqireSvc/getUlfptcaAlarmInfo";
        urlStr += "?" + URLEncoder.encode("serviceKey", "UTF-8") + "=" + serviceKey;
        urlStr += "&" + URLEncoder.encode("returnType", "UTF-8") + "=json";
        urlStr += "&" + URLEncoder.encode("numOfRows", "UTF-8") + "=10";
        urlStr += "&" + URLEncoder.encode("pageNo", "UTF-8") + "=1";
        urlStr += "&" + URLEncoder.encode("year", "UTF-8") + "=2021";

        URL url = new URL(urlStr);
        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();
        String result= sb.toString();

        // JSONParser를 이용해 String 값을 Json 객체로 만들어준다.
        JSONParser parser = new JSONParser();

        // 만들어진 JSON 객체를 JSONObject클래스를 사용해 저장한다.
        JSONObject obj = (JSONObject) parser.parse(result);

        //JSONObject에서 key값이 response인 value를 추출하기 위해 get()을 이용한다.
        JSONObject parse_response = (JSONObject) obj.get("response");

        //JSONObject에서 key값이 body인 value를 추출하기 위해 get()을 이용한다.
        JSONObject parse_body = (JSONObject) parse_response.get("body");

        //JSONObject에서 key값이 items인 value를 추출하기 위해 get()을 이용한다.
        JSONArray item = (JSONArray)parse_body.get("items");

        for(int i=0;i<item.size();i++){
            JSONObject tmp = (JSONObject)item.get(i);
            //System.out.println("item.get(i) : " + item.get(i) );
            String dataDate = (String)tmp.get("dataDate");
            String districtName = (String)tmp.get("districtName");
            String moveName = (String)tmp.get("moveName");
            String itemCode = (String)tmp.get("itemCode");
            String issueDate = (String)tmp.get("issueDate");
            String issueTime = (String)tmp.get("issueTime");
            String issueVal = (String)tmp.get("issueVal");
            String clearDate = (String)tmp.get("clearDate");
            String clearTime = (String)tmp.get("clearTime");
            String clearVal = (String)tmp.get("clearVal");
            System.out.println("발령일 : "+dataDate + ", 지역명 : "+districtName +", 권역명 : "+moveName +", 항목명 : "+itemCode + ", 경보단계 : "+issueDate + ", 발령일 : "+issueDate + ", 발령시간 : "+issueTime + ", 발령농도 : "+issueVal +", 해제일 : "+clearDate + ", 해제시간 : "+clearTime +", 해제농도 : "+clearVal);
        }
    }

}

결과

+ Recent posts