I am getting a response, which I converted to Pojo class with one field of type Object. Now when I am trying to cast the Object type to another Pojo class its throwing the error :
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to SecondClass
Code :
FirstClassResponse firstClassResponse = (FirstClassResponse) convertJSONToObject(firstClassResponseJson, FirstClassResponse.class); //jsonToObject method public static Object convertJSONToObject(String jsonRequest, Class objectClassType) throws Exception { Object object = gson.fromJson(jsonRequest, objectClassType); return object; }
Here, firsClass object when printed gives following result :
FirstClassResponse [modifiedResponse=null, response={id=123, username=abc, balance=0.0, currencycode=EUR, created=2021-03-30 16:31:54, agent_balance=0.0, sessionid=123}]
Now, the error happens in the following line :
SecondClassResponse modifiedResponse = (SecondClassResponse) firstClassResponse.getResponse(); java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to SecondClassResponse
I am sharing the POJO for FirstClassResponse and SecondClassResponse :
public class FirstClassResponse{ private SecondClassResponse modifiedResponse; private Object response; //getter, setter } public class SecondClassResponse{ private String id; private String username; private double balance; private String currencycode; private String created; private double agent_balance; private String sessionid; //getter, setter }
Advertisement
Answer
private Object response;
Make this a SecondClassResponse, not an Object. With it being an Object, GSON doesn’t know that this should be a SecondClassResponse, so it just shoves the map in there as a Map, which obviously can’t be cast.
The entire point of using GSON is to turn everything into specific objects so you can use it in a more Java like way. If you store something as an Object when converting from GSON, you’re almost always doing it wrong.