gpt4 book ai didi

java - 如何使用 Gson 库将 java.util.List 序列化为 Json?

转载 作者:行者123 更新时间:2023-11-29 17:24:31 24 4
gpt4 key购买 nike

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

请帮忙!

编辑: the final solution of this problem

最佳答案

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

关于java - 如何使用 Gson 库将 java.util.List<E> 序列化为 Json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10027268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com