如何在JSP中使用JSTL遍历JSON对象与JSON数组
处理JSON对象与遍历JSON数组的JSTL实现
现有JSON数据
单个JSON对象
{ "maxAgentAmt": 66, "minComAmt": 3, "maxTxn": 7, "maxAmt": 99, "minAmt": 3, "maxComAmt": 99 }
多对象JSON数组
[{ "comType": "V", "comValue": 5757, "comMode": "E", "maxAmt": 7575, "minAmt": 3, "comGSTMode": "E" }, { "comType": "E", "comValue": "E", "comMode": "V", "maxAmt": 8, "minAmt": 4, "comGSTMode": 8 }]
当前用于单个JSON对象的JSTL代码
<c:if test="${not empty list}"> <c:forEach items="${list.getJSONObject(\"maxAgentAmt\")}" var="list" varStatus="rowCounterCh"> <li>${maxAgentAmt}</li> </c:forEach> </c:if>
问题
目前能处理单个JSON对象,但不清楚如何遍历上述包含多个JSON对象的JSON数组。
遍历JSON数组的JSTL实现
假设你的JSON数组已被解析为JSTL可访问的Java集合(比如用Jackson/Gson将JSON字符串转为List<Map<String, Object>>),可直接用<c:forEach>遍历:
<c:if test="${not empty jsonArray}"> <ul> <c:forEach items="${jsonArray}" var="jsonObj" varStatus="rowStatus"> <li> 第${rowStatus.count}条数据:<br> comType: ${jsonObj.comType}<br> comValue: ${jsonObj.comValue}<br> maxAmt: ${jsonObj.maxAmt}<br> minAmt: ${jsonObj.minAmt} </li> </c:forEach> </ul> </c:if>
关键说明
<c:forEach>的items直接绑定JSON数组变量,var定义每个迭代的JSON对象别名,通过别名.属性名即可读取属性值。varStatus的count属性可获取当前迭代的序号(从1开始),index则是从0开始的索引。- 必须确保JSON数据已被正确解析为JSTL能识别的集合类型,否则无法直接遍历。
内容的提问来源于stack exchange,提问作者Akhilesh Dhiman
相关产品推荐
相关产品推荐

