Reputation: 369
When I have a list inside a generic method Gson returns a list of Object instead a list of generic type. I've seen a lot of threads with no solution, and if I dont use a generic method would have to create a method for each bean.
Is there any one with any idea what do I have to do so solve it?
PS: For a while I've created loop into the list to serialize entity by entity, splitting returned String and deserializing entity by entity, but clearly it's a workaround
Creating a generic list and serializing to JSON (this is a webservices method):
public String listEntity(String nomeClasse) throws WsException {
// Identifying the entity class
Class<?> clazz = Class.forName(nomeClasse);
// Querying with Hibernate
List<?> lst = getDao().listEntity(clazz);
// Check if is null
if (lst == null) {
return "[]";
}
return gson.toJson(lst);
}
Consuming the Webservice method:
public <T> List<T> listEntity(Class<T> clazz)
throws WsIntegracaoException {
try {
// Consuming remote method
String strJson = getService().listEntity(clazz.getName());
Type type = new TypeToken<List<T>>() {}.getType();
// HERE IS THE PROBLEM
List<T> lst = GSON.fromJson(strJson, type);
// RETURNS IS A LIST OF OBJECT INSTEAD OF A LIST OF <T>
return lst;
} catch (Exception e) {
throw new WsIntegracaoException(
"WS method error [listEntity()]", e);
}
}
Invoking the generic method:
List<City> list = listEntity(City.class);
// Here I get a ClassCastException
fillTable(list);
List Element (wrong):
java.lang.Object@23f6b8
Exception:
java.lang.ClassCastException: java.lang.Object cannot be cast to java.io.Serializable
Upvotes: 1
Views: 1767
Reputation: 369
SOLUTION - THIS WORKED FOR ME: Gson TypeToken with dynamic ArrayList item type
public <T> List<T> listEntity(Class<T> clazz)
throws WsIntegracaoException {
try {
// Consuming remote method
String strJson = getService().listEntity(clazz.getName());
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(strJson).getAsJsonArray();
List<T> lst = new ArrayList<T>();
for(final JsonElement json: array){
T entity = GSON.fromJson(json, clazz);
lst.add(entity);
}
return lst;
} catch (Exception e) {
throw new WsIntegracaoException(
"WS method error [listEntity()]", e);
}
}
Upvotes: 4