0

In a servlet inside method doPost I have created the code showed under here. It should do something very simple. Get an object according to a string passed by user request and pass this object to a response request. Unfortunately I get this exception

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)

I'm totally sure that reserv object is not empty but it is an entity fetched from the db . Do you know why I get this problem?

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

The class I'm trying to parse 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 call

$.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>");
        }

    });

Serializer

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;
    }
eng_mazzy
  • 1,049
  • 4
  • 23
  • 39
  • If possible, can you share a sample JSON string as well that are trying to parse? – Braj Jun 22 '14 at 13:43
  • I posted the object I'm trying to parse...maybe since it is composed from primitive fields and object fields as well I get that error – eng_mazzy Jun 22 '14 at 13:48
  • where is JSON string, Please share that as well. – Braj Jun 22 '14 at 13:53
  • What you mean? you mean the implementation of toString() method of reservation class? – eng_mazzy Jun 22 '14 at 13:55
  • This exception is usually the sign of a recursivity problem. For example, if your reservation object references a user or a route which itself references the reservation, etc. etc. ad infinitum. – JB Nizet Jun 22 '14 at 14:44
  • yes exactly I got a recursive exception...because User has list of reservation. route has user and reservation...but how can I fix the problem? – eng_mazzy Jun 22 '14 at 14:48
  • I've never used Gson. So i googled for Gson, which led me to the Gson userguide, starting with a table of contents containing the entry "Excluding Fields From Serialization and Deserialization". Click on it, and you hace all the needed explanations. Google is your friend. The documentation is your friend. It took me 10 seconds, literally, to find this information. https://sites.google.com/site/gson/gson-user-guide#TOC-Excluding-Fields-From-Serialization-and-Deserialization – JB Nizet Jun 22 '14 at 15:08

1 Answers1

0

You can try with Gson#toJson() that serializes the specified object into its equivalent Json String representation.

If you have cycle dependencies between objects then you need JsonSerializer to serialize the object into the JSON string as per your need.

Please have a look at below post to find a sample code:

For more info read gson-user-guide


I have tried below sample code and it works.

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

output:

{"name":"John","airport_city_source":"UK"}
Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • The problem is that when I do gson.toJson(reserv) I get an String. How could I access every field? – eng_mazzy Jun 22 '14 at 14:09
  • You are converting object to JSON string, Right? – Braj Jun 22 '14 at 14:10
  • @eng_mazzy: you have your Reservation object. If you want to access its fields, you don't need to transform it to JSON. – JB Nizet Jun 22 '14 at 14:11
  • yes reserv is an object which give me as result a string. After that as you may see I would access every field in the jquery function above – eng_mazzy Jun 22 '14 at 14:11
  • There is one more method [Gson#toJson()](https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html#toJson%28java.lang.Object%29) to covert JSON string back to object. – Braj Jun 22 '14 at 14:12
  • what are you passing `response.getWriter().println(myObj.toString());` just a simple JSON string. parse it in javascript at client side – Braj Jun 22 '14 at 14:13
  • @JBNizet Sorry maybe it was a misunderstanding. I would pass a json object from a servlet to a jquery function – eng_mazzy Jun 22 '14 at 14:13
  • What `application/json` means? – Braj Jun 22 '14 at 14:14
  • It means that the response is json type – eng_mazzy Jun 22 '14 at 14:14
  • 1
    JQuery runs in the browser. You need to send a JSON string to the browser as the HTTP response. And JQuery will then transform this JSON string into a JavaScript object. What you're currently doing is to transform a Java object to a JSON tree, and then the JSON tree to a JSON String (using toString()). That's useless, since the Java object can be transformed to a JSON string directly. – JB Nizet Jun 22 '14 at 14:14
  • here what I would like to do http://www.mysamplecode.com/2012/04/jquery-ajax-request-response-java.html – eng_mazzy Jun 22 '14 at 14:15
  • Simply pass a JSON string from Servlet and parse it at client side using [jquery.parsejson](http://api.jquery.com/jquery.parsejson/) – Braj Jun 22 '14 at 14:16
  • @Braj I'm going to try it...I didn't know that function you have right now suggested me – eng_mazzy Jun 22 '14 at 14:20
  • here the code the exception String reservObj = new Gson().toJson(reserv); – eng_mazzy Jun 22 '14 at 14:43
  • I have created a serializer to serialaze the object. Unfotunately this didn't help me to fix the problem – eng_mazzy Jun 22 '14 at 19:00
  • Just share all the POJO classes that your are trying to serialize. I'll try it. or edit in your post whatever you have tried. – Braj Jun 22 '14 at 19:05
  • I have updated the code. I get from that code a NullPointerException and I don't know why. I always use the debugger to check the object but here I have all the object. Ok I'm going to post all my updated code – eng_mazzy Jun 22 '14 at 19:05
  • One question. Inside POJO Reservation I have two object UserCredential and Route. Do I have to serialize them? – eng_mazzy Jun 22 '14 at 19:10
  • You don't need to serialize it because you are not sending it to the client. Only JSON string is send back to client. I tried your code and it works as edited in my post. Where are you getting `NullPointerException`? – Braj Jun 22 '14 at 19:22
  • Yes It's correct, just look at the object that is passed here `gson.toJson(reserv)`. You can put a `null` check some of fields are not mandatory. – Braj Jun 22 '14 at 19:24
  • The weird thing I get NullPointerException at this line Reservation reserv = reservationFacade.getValidReservation(reserv_id.toUpperCase()); but I have executed the debugger and I have seen the object reserv is not null – eng_mazzy Jun 22 '14 at 19:27
  • Where do you say to put null? – eng_mazzy Jun 22 '14 at 19:28
  • The problem is in `getValidReservation()` method. I suggest you try with an object as I created in my post. Create it manually and test it first. Put `null` check in `serialize` method for e.g `User` can be `null`. – Braj Jun 22 '14 at 19:30
  • the method getValidReservation get an object from the db. I'm going to try passing a simple object created by me – eng_mazzy Jun 22 '14 at 19:32
  • Sorry I can't help you any more. It's too late and going to sleep. Please take your time and first have a cup of Coffee and sit again and I'm sure you can solve it easily. Thanks. – Braj Jun 22 '14 at 19:36