views:

72

answers:

2

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 %>" 
   },                      

     <% 
     }
     %>   
}  ]    
A: 

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") %>
BalusC
Thank, this is quick and dirty sollution i was hoping for. I wil try GSON on the next occasion. tnx also for editting...
Chrizzz
OK. Rereading. This sounds really easy. I will try it now. Tnx again
Chrizzz
You're welcome.
BalusC
I had to do this as wel: rightclick the Java project, choose Build Path and then add the GSON jar's as new Library.
Chrizzz
Then you've wrongly chosen/prepared the project. It has to be a *Dynamic web project*.
BalusC
+5  A: 

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.

Stefan Kendall