4

I am sending a list of custom objects with model, and a JSP as a view. My custom object has a property called properties and it is JSONObject. This property will have the value as

{"services":[{"name":"abcd"},{"name":"efgh"}]}

now I want to iterate through the JSONArray [{"name":"abcd"},{"name":"efgh"}]. Here is what I am doing to loop through

<c:if test="${not empty customObject.services}">
                 <c:forEach items="${customObject.services.getJSONArray(\"services\")}" var="Service" varStatus="rowCounterCh">
                     <li>${Service.name}</li>
                  </c:forEach>
 </c:if>

But this is not able to iterate through the JSONArray. Am getting following error.

javax.servlet.ServletException: javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in &lt;forEach&gt;

So, what should I do to iterate through the JSONArray? Pls help

Taky
  • 5,284
  • 1
  • 20
  • 29
Seeker
  • 2,405
  • 5
  • 46
  • 80

2 Answers2

9

I have something like this

<c:forEach begin="0" end="${jsonArray.length() -1}" var="index">
     ${jsonArray.getJSONObject(index).getString("name")}
</c:forEach>

replace ${jsonArray.length() -1} with your jsonArray. In this case, it is something like this

${customObject.services.getJSONArray(\"services\").length()}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
skuarch
  • 115
  • 1
  • 3
2

For each tag should require a base interface for your items. JSONArray neither java.util.Collection nor java.util.Iterable. So For each tag implementation cannot iterate over the collection you pass into items attribute.

To solve this problem you may:

  1. Generate HTML list view with JSP.
  2. Or list item convert JSONArray into some appropriate Collection in customObject.services.getJSONArray method. JSONArray in gson implementation should has method: iterator, because it implements the Iterable interface. Try to return an com.google.gson.JSONArray#iterator() instead of JSONArray in your #getJSONArray(String) method.

more detailed explanation

Community
  • 1
  • 1
Taky
  • 5,284
  • 1
  • 20
  • 29
  • I thought of getting the JSONarray and work upon that inside scriptlet, as `var itemStr ='';` but this is giving me the json array as [{"name":"abcd"},{"name":"efgh"}] which is all the "s are replaced with " how can I avoid this? – Seeker Jan 22 '13 at 11:54
  • 1
    Try to set escapeXml attribute to false: http://www.tutorialspoint.com/jsp/jstl_core_out_tag.htm – Taky Jan 22 '13 at 12:33