Deserialize json string with gson

My Java servlet returns a json string like this:

Gson gson = new Gson(); String lista = gson.toJson(utenti); System.out.println(lista); request.setAttribute("lista", lista); request.getRequestDispatcher("GestioneUtenti.jsp").forward(request, response); 

now, on the jsp page, I want to get my List array again. I am trying to do this:

 <% String lista = (String)request.getAttribute("lista"); Gson gson = new Gson(); ArrayList<Utente> users = gson.fromJson(lista, TypeToken.get(new ArrayList<Utente>().getClass()).getType()); out.println(users.get(0).getUsername()); %> 

I have this exception:

 java.lang.ClassCastException: com.google.gson.internal.StringMap cannot be cast to classi.Utente 

Can you help me? If I miss some details, tell me! thanks: -)

+5
source share
2 answers

I solved with this code:

 String lista = (String)request.getAttribute("lista"); Gson gson = new Gson(); Type listType = new TypeToken<ArrayList<Utente>>() {}.getType(); ArrayList<Utente> users = new Gson().fromJson(lista, listType); 
+10
source

It is assumed that you have a StringMap where you declared the Utente class. The source of the error is a more than likely list of users.

0
source

All Articles