Search code examples
jspjsp-tags

How to parse JSON array in JSP and form a String


I have a JSON array of strings which is nothing but the response received from a server. Now I would like iterate through the array object and form a single string and, perform string manipulation on the whole string. For example, I have the following JSON object

      "data": {
          "details": [
            "Toyota",
            "Mazda",
            "Hyundai"
          ]
        }

I knew that I can simply print it as an HTML element using ForEach as below,

<c:forEach items="${details}" var="item" varStatus="status">
    <c:if test="${!status.last}
      <span>${item}, </span>
    </c:if>
    <c:if test="${status.last}">
      <span>and ${item}</span>
    </c:if>
</c:forEach>

But here I do not want to in this manner but like to form a complete string like Toyota Mazda Hyundai and then JSP Standard Tag Library as indicated here, then pass that string as an argument to i18n key like as below,

snippet from i18n common properties,

car.makers=Car makers {0}

snippet from my jsp

<c:set var="carmakers"><fmt:message key="car.makers"><fmt:param>${thefullstring}</fmt:param></fmt:message></c:set> 

The full string is the one which I'm trying to generate out of JSON array. How to form a String from JSON array.


Solution

  • I figured it out on how to format a String from the JSON array. The implementation is as below,

      <c:set var="models" value=""/>
      <c:forEach items="${carmodels}" var="item" varStatus="status">
        <c:if test="${!status.last}">
            <c:set var="models" value="${models}${item},${' '}"/>
        </c:if>
        <c:if test="${status.last}">
          <c:choose>
            <c:when test="${not empty models}">
              <c:set var="models" value="${models}and${' '}${item}"/>
            </c:when>
            <c:otherwise>
              <c:set var="models" value="${item}"/>
            </c:otherwise>
          </c:choose>
        </c:if>
      </c:forEach>