Skip to content
Advertisement

Object not being able to map to POJO class

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 :

JavaScript

Code :

JavaScript

Here, firsClass object when printed gives following result :

JavaScript

Now, the error happens in the following line :

JavaScript

I am sharing the POJO for FirstClassResponse and SecondClassResponse :

JavaScript

Advertisement

Answer

JavaScript

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement