Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deserialize json string with gson

My java servlet returns a json string in this way:

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, in the jsp page I want to have my arrayList again. I try 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 Youu help me? If i miss some particulars tell me! thanks :-)

like image 875
Martina Avatar asked Feb 03 '13 14:02

Martina


People also ask

How do I deserialize JSON?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

Does Gson ignore extra fields?

As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.

What is GsonBuilder in Java?

public GsonBuilder() Creates a GsonBuilder instance that can be used to build Gson with various configuration settings. GsonBuilder follows the builder pattern, and it is typically used by first invoking various configuration methods to set desired options, and finally calling create() .


1 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);
like image 82
Martina Avatar answered Sep 28 '22 01:09

Martina