Christian Loncle
Christian Loncle

Reputation: 1584

writing JSON with JSP

You would probably do this automatically with some library. But I am new with Java and JSON and I need a quick sollution.

What I would like is to write down (echo) JSON out of a JSP file. So far so good, but now I have a list of objects. So I start a fast enumeration.

And now the question: how do I close the JSON array with }] instead of ,? Normally I put a nill or null in the and.

Here is my loop:

 "rides":[{  
<% 
List<Ride> rides = (List<Ride>)request.getAttribute("matchingRides");
            for (Ride ride : rides) { 
%>               
 "ride":{     
     "rideId":"<%= String.valueOf(ride.getId()) %>",
   "freeText":"<%= freeText %>" 
   },                      

     <% 
     }
     %>   
}  ]    

Upvotes: 0

Views: 5365

Answers (2)

BalusC
BalusC

Reputation: 1108712

Iterate using an Iterator instead. This way you can check at end of the loop if Iterator#hasNext() returns true and then print the ,.

// Print start of array.
Iterator<Ride> iter = rides.iterator();
while (iter.hasNext()) { 
    Ride ride = iter.next();
    // Print ride.

    if (iter.hasNext()) {
       // Print comma.
    }
}
// Print end of array.

Regardless, I strongly recommend to use a JSON serializer for this instead of fiddling low level like that. One of my favourites is Google Gson. Just download and drop the JAR in /WEB-INF/lib. This way you can end up with the following in the servlet:

request.setAttribute("matchingRides", new Gson().toJson(matchingRides));

and the following in JSP:

${matchingRides}

or with the old fashioned scriptlet as in your question:

<%= request.getAttribute("matchingRides") %>

Upvotes: 0

Stefan Kendall
Stefan Kendall

Reputation: 67822

1.) Download and setup GSON in your application container.
2.)

GSON gson = new GSON();
<%= gson.toJson( rides ) %>;

You'll save yourself time in the short run and long run if you avoid the path of insanity.

Upvotes: 5

Related Questions