(JAVA) Naver API로 가져온 JSON을 GSON으로 Parse하기
네이버 API를 통해 서버에서 넘어온 Json을 파싱하는 법을 알아보겠다.
GSON을 이용한다.
먼저 프로젝트에 GSON을 Import하자. (설명은 여기)
그 다음 애플리케이션 등록을 하자 (등록은 여기)
자세한 등록 방법은 설명하지 않겠다.
등록을 마치면 클라이언트 키와 비밀번호를 발급받는다.
그 후 코드를 작성하자.
public class ShopInformDTO {
public String lastBuildDate;
public int total;
public int start;
public int display;
public Item[] items;
class Item {
public String title;
public String link;
public String category;
public String description;
public String telephone;
public String address;
public String roadAddress;
public String mapx;
public String mapy;
}
}
public class Main {
public static void main(String[] args) {
int cnt = 1; // 출력 갯수
String clientId = "안알랴줌";
String clientSecret = "안알랴줌";
String temp_json;
String json = "";
String search_word;
ShopInformDTO inform;
BufferedReader br;
Scanner scan = new Scanner(System.in); // for 입력URLConnection urlConn;
URL url;
try {
search_word = URLEncoder.encode(scan.nextLine(), "UTF-8"); // 검색어
url = new URL("https://openapi.naver.com/v1/search/local.json?query=" + search_word + "&display=" + 100); //API 기본정보의 요청 url을 복사해오고 필수인 query를 적어줍니당!
urlConn = url.openConnection(); //openConnection 해당 요청에 대해서 쓸 수 있는 connection 객체
urlConn.setRequestProperty("X-Naver-Client-ID", clientId);
urlConn.setRequestProperty("X-Naver-Client-Secret", clientSecret); // do not setting,
br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while ((temp_json = br.readLine()) != null) {
json += temp_json;
}
json = json.trim();
} catch (Exception e) {
System.out.println("ERROR");
e.printStackTrace();
}
inform = new Gson().fromJson(json, ShopInformDTO.class);
}
}
코드에 대한 설명은 하지 않겠다. 긴 코드도 아니고, 만약 이해가 안된다면 해매야한다. 그게 우리가 할 일 이니까.
쿼리문은 설명이 필요할 것 같다. 그래서 문서 링크를 첨부한다.
https://developers.naver.com/docs/search/blog/
이것만 보면 별거 아닌 코드처럼 보인다.
사실 그렇다. 별거 아닌 코드다. 내가 며칠 해맸던 이유는 json 파싱 결과를 DTO에 넣는것을 어떻게 해야 하는건지 몰랐기 때문이다.
출력되는 json의 구조는 이러하다.
{
"lastBuildDate": "Mon, 16 Jul 2018 01:28:44 +0900",
"total": 2,
"start": 1,
"display": 2,
"items": [{
"title": "<b>설빙</b> 경기광명철산점",
"link": "http://sulbing.com/",
"category": "카페,디저트>빙수",
"description": "디저트 카페, 빙수, 토스트, 커피, 스무디, 녹차라떼, 오미자차 등 판매.",
"telephone": "02-2611-1478",
"address": "경기도 광명시 철산동 410",
"roadAddress": "경기도 광명시 오리로856번길 8-1",
"mapx": "300065",
"mapy": "542034"
}, {
"title": "<b>설빙</b> 하안점",
"link": "",
"category": "카페,디저트>빙수",
"description": "경기도 광명시 하안동 위치, 디저트카페, 빙수 전문점.",
"telephone": "02-899-0503",
"address": "경기도 광명시 하안동 34-3",
"roadAddress": "경기도 광명시 하안로 309 세인빌딩",
"mapx": "301042",
"mapy": "540690"
}]
}
items안에 array 형식으로 값이 존재한다.
gson 사용법을 구글링 해봤을때 이런 형식을 파싱하는 법은 보이지 않았다. (어딘가에 있었겠지...)
단순히 array값을 어떻게 파싱을 해야할지 감이 잡히지 않았었다.
그래서 스택오버플로우에 직접 물어본 결과는 저 위의 DTO를 만들고 items 배열을 만들어 파싱을 해야한다.
https://stackoverflow.com/questions/51350347/how-to-parse-jsonitems