deserialize json string with gson

徘徊边缘 提交于 2019-12-19 07:35:26

问题


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 :-)


回答1:


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);



回答2:


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



来源:https://stackoverflow.com/questions/14673694/deserialize-json-string-with-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!