小编典典

如何序列化java.util.List 使用Gson库访问Json吗?

java

在我的servlet中,我有以下代码:

    response.setContentType("application/json");//set json content type
    PrintWriter out = response.getWriter();

   EntityManagerFactory emf=Persistence.createEntityManagerFactory("webPU");
   GpsJpaController gjc=new GpsJpaController(emf);    
   java.util.List<Gps> listGps=gjc.findGpsEntities();//retrieve the list of GPS from DB

   Gson gson=new Gson();
   String json=gson.toJson(listGps); //convert List<Gps> to json
   out.println(json);

使用以下代码从ajax返回响应:

$.ajax({ 
           type: "GET", 
           url: "getInfoGeoActive",
           dataType: 'json',
           error: function(xhr, ajaxOptions, thrownError){ $("#content").empty().append("* Error from server cause: "+thrownError).addClass("error"); } ,
           success:function(data){$("#content").empty().append(data);}
             });

当我运行代码时,我仍然收到以下错误(来自ajax):

  Error from server cause:Internal Servlet Error

我还尝试List<Gps>在没有ajax的同一java页面中显示序列化对象,如下所示:

EntityManagerFactory emf=Persistence.createEntityManagerFactory("JavaApplication21PU");
        GpsJpaController gjc=new GpsJpaController(emf);
        java.util.List<Gps> listGps=gjc.findGpsEntities();

        Gson gson=new Gson();
        String json=gson.toJson(listGps);

        System.out.println(json);

我收到此错误:

Exception in thread "main" java.lang.StackOverflowError
    at java.lang.StrictMath.floorOrCeil(StrictMath.java:355)
    at java.lang.StrictMath.floor(StrictMath.java:340)
    at java.lang.Math.floor(Math.java:424)
    at sun.misc.FloatingDecimal.dtoa(FloatingDecimal.java:620)
    at sun.misc.FloatingDecimal.<init>(FloatingDecimal.java:459)
    at java.lang.Double.toString(Double.java:196)
    at java.lang.Double.toString(Double.java:633)
    at com.google.gson.stream.JsonWriter.value(JsonWriter.java:441)
    at com.google.gson.Gson$4.write(Gson.java:270)
    at com.google.gson.Gson$4.write(Gson.java:255)

请帮忙!

编辑此问题的最终解决方案


阅读 211

收藏
2020-11-26

共1个答案

小编典典

由于无限递归,发生 Exception 。您可能需要彻底检查代码,以防任何意外的递归。

2020-11-26