Java/Java Library
[Java Library] gson casting 오류 com.google.gson.internal.LinkedTreeMap cannot be cast to my class - jsonlist 를 List 객체로 만들기
곰돌이쿤
2021. 1. 28. 15:42
반응형
Gson casting 오류
gson 을 사용하다 보면
__com.google.gson.internal.LinkedTreeMap cannot be cast to my class__
이런 오류가 나는데, casting 을 사용하려고 하면 나는 오류다.
Gson gson = new Gson();
list = gson.fromJson(jsonString, new TypeToken<List<T>>(){}.getType());
jsonString list 로 fromJson 하는 경우에 생기는 오류이다.
결론은 아래 메소드로 다시 json 변환 후 object 로 변환 하던지, 아니면 gson 파싱 객체를 casting하지 않도록 만들어야 한다.
//array 를 json String 으로 변환
public static <T> String arrayToString(ArrayList<T> list) {
Gson g = new Gson();
return g.toJson(list);
}
// json String 을 list Object 로 변환
public static <T> List<T> stringToArray(String s, Class<T[]> clazz) {
T[] arr = new Gson().fromJson(s, clazz);
return Arrays.asList(arr); //or return Arrays.asList(new Gson().fromJson(s, clazz)); for a one-liner
}
참고문헌
https://stackoverflow.com/questions/27253555/com-google-gson-internal-linkedtreemap-cannot-be-cast-to-my-class
www.programmersought.com/article/46923204627/
반응형