본문 바로가기

Android/Basic

[Android] Gson을 이용한 JSON 변환

자바스크립트의 경우 JSON과 포맷이 같기 때문에 따로 변환해줄 필요가 없는데, 자바에서 JSON 객체를 다루기 위해서는 자바 객체로의 변환이 필요하다.


Gson은 구글에서 만든 JSON 문자열을 객체로 변환해주는 라이브러리이다.


* 샘플 API 주소 : http://www.kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?key=430156241533f1d058c603178cc3ca0e&targetDt=20120101


외부라이브러리 이므로 gradle에 다음 한줄을 추가해준다.

implementation 'com.google.code.gson:gson:2.8.2'


사이트에 가서 확인해보면 JSON형태로 되어있는 것을 볼 수 있는데, JSON 형식 안에 들어있는 속성에 맞게 그대로 클래스를 정의해주어야 한다.

객체 안에 객체가 포함되어 있는 형식으로 되어있는데, 자바에서도 마찬가지로 객체 안에서 객체를 정의하면 된다.

주의할 점은 JSON 형식에서의 속성 이름과 동일하게 클래스를 정의해야 한다는 것이다.

총 3개의 클래스를 정의했다.

public class MovieList {
MovieListResult boxOfficeResult;
}
public class MovieListResult {
String boxofficeType;
String showRange;

ArrayList<Movie> dailyBoxOfficeList = new ArrayList<Movie>();
}
public class Movie {
String rnum;
String rank;
String rankInten;
String rankOldAndNew;
String movieCd;
String movieNm;
String openDt;
String salesAmt;
String salesShare;
String salesInten;
String salesChange;
String salesAcc;
String audiCnt;
String audiInten;
String audiChange;
String audiAcc;
String scrnCnt;
String showCnt;
}


Gson 객체를 생성해서 변환.

Gson gson = new Gson();
MovieList movieList = gson.fromJson(response, MovieList.class);

정의한 클래스 그대로, 자동으로 변환해준다. 완전 편리!