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 %>"
},
<%
}
%>
} ]
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 %>"
},
<%
}
%>
} ]
Share
Improve this question
edited Oct 15, 2010 at 15:53
BalusC
1.1m376 gold badges3.7k silver badges3.6k bronze badges
asked Oct 15, 2010 at 15:51
Christian LoncleChristian Loncle
1,5843 gold badges20 silver badges30 bronze badges
2 Answers
Reset to default 51.) 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.
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 ma.
}
}
// Print end of array.
Regardless, I strongly remend 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") %>