admin管理员组文章数量:1421196
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") %>
本文标签: javawriting JSON with JSPStack Overflow
版权声明:本文标题:java - writing JSON with JSP - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745348589a2654624.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论