본문 바로가기
TIL/Java

GSON Type 정의 관련 정리

by DandyU 2017. 11. 21.

JAVA에서 GSON으로 리스트 형태의 데이터를 변환하는 경우  

아래와 같이 Type 인스턴스를 생성해서 적용해줘야 컴파일 에러가 나지 않습니다.


Type type = new TypeToken<List<PrvtMappingInfo>>() {}.getType();

gson.toJson(mappingInfoList, type));

gson.fromJson(jsonString, type);


또한, Generic Type을 사용하는 클래스를 GSON을 사용해서 JSON으로 변환하고, 클래스로 다시 변환하는 경우

아래와 같은 Exception이 발생하는 경우가 있는데요.


"com.google.gson.internal.LinkedHashTreeMap cannot be cast to my object"


이건 Generic Type을 사용해서 발생하는 문제이고 Type 정보를 구체적으로 명시해줘야 해요.

저같은 경우 동적으로 Type 정보를 설정해주기 위해 아래과 같이 Type 정보를 생성하였습니다.


public class Wrapper<T> {

protected String fileName;

protected Long createdTime;

protected List<T> data;

}


public class FragmentSet {

protected Schedule schedule;

protected ArrayList<Content> contentList;

}


Type type = TypeToken.getParameterized(Wrapper.class, FragmentSet .class).getType();


이렇게 하지 않으면 아래와 같이 해줘야 하는데요. 이건 동적으로 Type 정보를 설정할 수 없어서 위와 같이 했습니다.

참고로 getParameterized () 메소드는 GSON 2.8.0 버전부터 지원한다고 하네요.


Type type = new TypeToken<Wrapper<FragmentSet >>() {}.getType();



Sinnce gson 2.8.0, you can use TypeToken#getParametized((Type rawType, Type... typeArguments)) to create the typeToken, then getType() should do the trick.


For example:


TypeToken.getParameterized(ArrayList.class, myClass).getType();




댓글