I have this problem: in my sql database I have a table Utente with the primary key IDUtente that is of type INT and is Auto Incremental.
in the db I have:
ID|Name|....
1|Name1|....
2|Name2|....
in the Java servlet I read data from the database and I serialize data with Gson in this way:
Gson gson = new Gson();
String lista = gson.toJson(utenti);
request.setAttribute("lista", lista);
request.getRequestDispatcher("GestioneUtenti.jsp").forward(request, response);
and here it’s ok because the string lista it’s equals to:
[{"idUtente":1,"username":"a","password":"a","nome":"a","cognome":"a","dataNascita":"dic 12, 1988","telefono":"3200769667","indirizzo":"a","citta":"a","luogoDiNascita":"a","abbonamentiATempo":0,"abbonamentiAPunti":0,"dataIscrizione":"dic 12, 2000","posizione":"socio","email":"a"},{"idUtente":2,"username":"b","password":"b","nome":"b","cognome":"b","dataNascita":"giu 25, 1960","telefono":"3474213142","indirizzo":"b","citta":"b","luogoDiNascita":"b","abbonamentiATempo":0,"abbonamentiAPunti":0,"dataIscrizione":"mar 11, 2001","posizione":"non socio","email":"b"}]
In my JSP page now I have to deserialize the string and I do this in this way:
<%String lista = (String)request.getAttribute("lista");
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
Type listType = new TypeToken<ArrayList<Utente>>() {}.getType();
ArrayList<Utente> users = gson.fromJson(lista, listType);
for(int i=0;i<users.size();i++){
out.print("<tr>");
out.print("<td>"+users.get(i).getIdUtente()+"</td>");
out.print("<td>"+users.get(i).getNome()+"</td>");
out.print("<td>"+users.get(i).getCognome()+"</td>");
out.print("<td>"+users.get(i).getPosizione()+"</td>");
out.print("<td>"+users.get(i).getTelefono()+"</td>");
}
The problem is that The IDs printed are always equals to 0! Why?
If it is necessary I’ll write also my class Utente!
Why are you serializing utenti to JSON, putting it on the request then deserializing it in the JSP?
Just put the list in the request and extract the List as you are the string – no GSON needed.
Now if you were putting this across the wire to the client, THEN I can see the need for GSON but not in your particular usage case.
You’re entire operation is taking place within the server, so there is no need for you to serialize the utenti list instance.