본문 바로가기

 

[JAVA/JSON] simple json parser, 공공데이터 날씨예보를 이용한 날씨정보 수집하기 

 

포스팅을 시작하겠습니다.

 

우선 우선적으로 받을 것은 simple json 입니다.

 

 

<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->

<dependency>

    <groupId>com.googlecode.json-simple</groupId>

    <artifactId>json-simple</artifactId>

    <version>1.1.1</version>

</dependency>

 

 

https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1

 

위 url에 접속하여 파일을 받아서 사용하셔도 됩니다.

 

 

 

이번에 수집할 자료는 

 

공공데이터 포털

 

https://www.data.go.kr

 

에서 제공하는 동네예보정보조회서비스 에서 

 

초단기실황조회 서비스를 이용할 것입니다.

 

 

 

 

API 신청을 하게 되면 아래와 같은 화면을 마이페이지에서 볼 수 있습니다.

 

 

 

 

서비스키를 입력하고 base_date, base_time을 입력하여 결과를 확인해 봅시다.

 

{"response":{"header":{"resultCode":"0000","resultMsg":"OK"},"body":{"items":{"item":[{"baseDate":20171212,"baseTime":1000,"category":"LGT","nx":60,"ny":127,"obsrValue":0},{"baseDate":20171212,"baseTime":1000,"category":"PTY","nx":60,"ny":127,"obsrValue":0},{"baseDate":20171212,"baseTime":1000,"category":"REH","nx":60,"ny":127,"obsrValue":33},{"baseDate":20171212,"baseTime":1000,"category":"RN1","nx":60,"ny":127,"obsrValue":0},{"baseDate":20171212,"baseTime":1000,"category":"SKY","nx":60,"ny":127,"obsrValue":1},{"baseDate":20171212,"baseTime":1000,"category":"T1H","nx":60,"ny":127,"obsrValue":-9.5},{"baseDate":20171212,"baseTime":1000,"category":"UUU","nx":60,"ny":127,"obsrValue":2.6},{"baseDate":20171212,"baseTime":1000,"category":"VEC","nx":60,"ny":127,"obsrValue":306},{"baseDate":20171212,"baseTime":1000,"category":"VVV","nx":60,"ny":127,"obsrValue":-1.8},{"baseDate":20171212,"baseTime":1000,"category":"WSD","nx":60,"ny":127,"obsrValue":3.2}]},"numOfRows":10,"pageNo":1,"totalCount":10}}}

 

위와같이 나오네요

 

그럼 활용해 봅시다.

 

 

public interface WeatherKeyInfo {
    String SERVICEKEY = "servicekey";
    int[][] REGION = {{60,127},{60,120},{98,76},{52,38}};  // SEOUL , GYEONGGI ,  BUSAN , JEJU
    String[] LOCATION = {"SEOUL", "GYEONGGI", "BUSAN", "JEJU"};
}

servicekey에는 본인의 서비스키를 넣어주세요.

 

지역에 대한 nx, ny 값은 

 

서비스 정보에 zip 파일을 다운받아서 확인 하시길 바랍니다.

 

public class DateLoader {
    public String DateLoader(){
        Date date = new Date();
        SimpleDateFormat sformat = new SimpleDateFormat("yyyyMMdd HHmm");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(calendar.HOUR, -1);
        String now = sformat.format(calendar.getTime());

        return now;
    }
}

 

위는 현재 시간에서 1시간전을 구하는 소스코드 입니다.

 

 

public class HtmlParser {
    public String HtmlParser(String urlToRead) {
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(urlToRead);
            InputStream is = url.openStream();
            int ch;

            while ((ch = is.read()) != -1) {
                //System.out.print((char) ch);
                result.append((char) ch);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }
}

 

위는 Json 형태를 읽어 오기위한 소스코드입니다.

 

 

String now = new DateLoader().DateLoader();

System.out.println(now);
for (int j=0; j<REGION.length; j++) {
    weatherStrUrl.setLength(0);
    weatherStrUrl.append("http://newsky2.kma.go.kr/service/SecndSrtpdFrcstInfoService2/ForecastGrib?serviceKey=" +
            SERVICEKEY + "&base_date=" + now.substring(0, 8) + "&base_time=" + now.substring(9, 13));
    weatherStrUrl.append("&nx=" + REGION[j][0] + "&ny=" + REGION[j][1] + "&numOfRows=10&pageSize=10&pageNo=1&startPage=1&_type=json");
    String jsonSouce = new HtmlParser().HtmlParser(weatherStrUrl.toString());

    try {
        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonSouce);
        JSONObject response = (JSONObject) jsonObject.get("response");
        JSONObject body = (JSONObject) response.get("body");
        JSONObject items = (JSONObject) body.get("items");
        JSONArray item = (JSONArray) items.get("item");

        JSONObject weatherInfo = (JSONObject) item.get(0);
        weatherDto.setBaseDate(weatherInfo.get("baseDate").toString());
        weatherDto.setBaseTime(weatherInfo.get("baseTime").toString());
        weatherDto.setLOCATION(LOCATION[j]);


        for (int i = 0; i < item.size(); i++) {
            weatherInfo = (JSONObject) item.get(i);
            if (weatherInfo.get("category").equals("T1H")) {
                weatherDto.setT1H(Double.parseDouble(weatherInfo.get("obsrValue").toString()));
            } else if (weatherInfo.get("category").equals("RN1")) {
                weatherDto.setRN1(Double.parseDouble(weatherInfo.get("obsrValue").toString()));
            } else if (weatherInfo.get("category").equals("SKY")) {
                weatherDto.setSKY(Double.parseDouble(weatherInfo.get("obsrValue").toString()));
            } else if (weatherInfo.get("category").equals("PTY")) {
                weatherDto.setPTY(Double.parseDouble(weatherInfo.get("obsrValue").toString()));
            } else if (weatherInfo.get("category").equals("LGT")) {
                weatherDto.setLGT(Double.parseDouble(weatherInfo.get("obsrValue").toString()));
            } else if (weatherInfo.get("category").equals("VEC")) {
                weatherDto.setVEC(Double.parseDouble(weatherInfo.get("obsrValue").toString()));
            } else if (weatherInfo.get("category").equals("WSD")) {
                weatherDto.setWSD(Double.parseDouble(weatherInfo.get("obsrValue").toString()));
            } else if (weatherInfo.get("category").equals("REH")) {
                weatherDto.setREH(Double.parseDouble(weatherInfo.get("obsrValue").toString()));
            }
        }
    } catch (Exception e) {
        e.getMessage();
    }
    weatherDao.insertinfo(weatherDto);
}
System.out.println("업데이트 완료");
 

현재시간 한시간 전을 받아와서 서비스키와 NX, NY 갑을 넣어 준 후

 

htmlParser를 이용하여 해당 페이지를 읽어옵니다.

 

그후 Simple Json 을 이용하여 수집해봅니다.

 

저는 하니씩 안으로 들어가서 item을 가져왔는데

 

너무 무식한 것 같아요 다른 방법이 있으면 알려주세요.... ㅠㅠ

 

이 후 category 란을 비교하여 값을 가져와 값을 입력하여 DB에 저장하는 소스코드 입니다.

 

위와 같이 활용하여 사용하시면 됩니다.

 

 

아래는 Dto 파일

 

 

 

다 Double로 할 필요는 없습니다. 

 

확인하시고 올바른 자료형을 사용하세요

 

 

아래는 뿌려줍니다.

 

 

 

jstl을 활용하여 뿌려줍니다.

 

 

실행화면

 

 

 

전체 코드

https://github.com/shing100/WeatherProject

 

shing100/WeatherProject

기상청 API를 활용하여 날씨정보확인 사이트 개발 . Contribute to shing100/WeatherProject development by creating an account on GitHub.

github.com

 

 

이상으로 포스팅을 마치겠습니다.

 

엉망진창

개인 블로그 입니다. 코딩, 맛집, 정부정책, 서비스, ~방법 등 다양한 정보를 소개합니다