使用gson类时获取stackoverflow异常

时间:2014-06-22 13:34:05

标签: java gson

在一个servlet里面的方法doPost我创建了这里显示的代码。它应该做一些非常简单的事情。根据用户请求传递的字符串获取对象,并将此对象传递给响应请求。不幸的是我得到了这个例外

java.lang.NullPointerException
    at it.volaconnoi.servlet.CheckInServlet.doPost(CheckInServlet.java:68)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)

我完全确定reserv对象不是空的,但它是从db获取的实体。你知道我为什么会遇到这个问题吗?

CODE UPDATED

 @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException 
{
    String reserv_id = request.getParameter("reserv_id");

    Reservation reserv = reservationFacade.getValidReservation(reserv_id.toUpperCase());

    Gson gson = new GsonBuilder().registerTypeAdapter(Reservation.class, new ReservationSerializer())
                                 .create();      

    response.setContentType("application/json");

    PrintWriter out = response.getWriter();

    out.print(gson.toJson(reserv));    
    out.flush();
}

我正在尝试解析POJO objec

public class Reservation implements Serializable
{
    private String id_reservation;

    private int passengers;

    private int luggages;

    private float price;


    private Date date_reservation;

    private boolean cancelled;

    private UserCredential user;

    private Route route;

    ... getter and setter

Jquery调用

$.post("checkin", {reserv_id :reserv_id}, function(data){

        if(data.success)
        {
            $("#result_check_in").html("");
            $("#result_check_in").append("<table class='show_reservations'>");
            $("#result_check_in").append("<tr>");
            $("#result_check_in").append("<td>" + data.reserv_client.id + "<td>");
            $("#result_check_in").append("<td>" + data.reserv_client.user.name + "<td>");
            $("#result_check_in").append("<td>" + data.reserv_client.user.surname + "<td>");
            $("#result_check_in").append("</tr>");
            $("#result_check_in").append("</table>");
        }
        else
        {
            $("#result_check_in").append("<p>Non è stata trovata alcuna prenotazione corrispondente al PNR inserito!</p>");
        }

    });

串行

public class ReservationSerializer implements JsonSerializer<Reservation>
{
    @Override
    public JsonElement serialize(Reservation r, Type type, JsonSerializationContext jsc) 
    {
        JsonObject json = new JsonObject();

        json.add("id", new JsonPrimitive(r.getId()));

        json.add("name", new JsonPrimitive(r.getUsername().getName()));
        json.add("surname", new JsonPrimitive(r.getUsername().getSurname()));

        json.add("airport_departure", new JsonPrimitive(r.getRoute().getAirport_city_source().getName()));
        json.add("airport_arrival", new JsonPrimitive(r.getRoute().getAirport_city_dest().getName()));

        json.add("date_departure", new JsonPrimitive(dateToString(r.getRoute().getDeparture_date())));
        json.add("date_arrival", new JsonPrimitive(dateToString(r.getRoute().getArrival_date())));

        json.add("passengers", new JsonPrimitive(r.getPassengers()));
        json.add("luggages", new JsonPrimitive(r.getLuggages()));

        return json;
    }

1 个答案:

答案 0 :(得分:0)

您可以尝试使用Gson#toJson()将指定对象序列化为等效的Json String表示。

如果对象之间存在循环依赖关系,则需要JsonSerializer根据需要将对象序列化为JSON字符串。

请查看以下帖子以查找示例代码:

有关详细信息,请参阅gson-user-guide


我尝试了下面的示例代码,但它确实有效。

class Reservation {    
    private UserCredential user;
    private String airport_city_source;    
   // getter & setter     
}

class UserCredential {
    private String username;    
   // getter & setter    
}

class ReservationSerializer implements JsonSerializer<Reservation> {
    @Override
    public JsonElement serialize(Reservation r, Type type, JsonSerializationContext jsc) {
        JsonObject json = new JsonObject();

        json.add("name", new JsonPrimitive(r.getUser().getUsername()));
        json.add("airport_city_source", new JsonPrimitive(r.getAirport_city_source()));

        return json;
    }
}

Reservation reserv = new Reservation();
UserCredential user = new UserCredential();
user.setUsername("John");
reserv.setUser(user);
reserv.setAirport_city_source("UK");

Gson gson = new GsonBuilder().registerTypeAdapter(Reservation.class,
        new ReservationSerializer()).create();

System.out.println(gson.toJson(reserv));

输出:

{"name":"John","airport_city_source":"UK"}