【问题标题】:How to serialize a java.util.List<E> to Json using Gson Library?如何使用 Gson 库将 java.util.List<E> 序列化为 Json?
【发布时间】:2012-04-19 02:44:35
【问题描述】:

在我的 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

我也试过在没有ajax的同一个java页面中显示序列化对象List&lt;Gps&gt;,如下:

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)

请帮忙!

编辑: the final solution of this problem

【问题讨论】:

    标签: java javascript json gson


    【解决方案1】:

    StackOverflowException 由于无限递归而发生。您可能需要彻底检查代码是否有任何意外递归。

    【解决方案2】:

    您的 Gps 对象似乎包含对其自身的引用。

    【讨论】:

    • 考虑到它是在 Gson 转换为 json 时发生的,我猜@ahanin 是对的。 Gps 可能是罪魁祸首。
    猜你喜欢
    • 1970-01-01
    • 2013-09-03
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    相关资源
    最近更新 更多