Search code examples
jspliferayjspdf-autotable

jsp to convert JsonArray elements


I am creating my array as such that has a key value (Name and Email) like this and with a loop populating as below:

for(x y : model) {
             
               obj_JSONObject1.append(x.getName(), x.getValue()); 
              
        }
            jsonArray.put(obj_JSONObject1);

My Array looks like this:

[
  {
"Email": [
      "[email protected]",
      "[email protected]"
    ],
    "Name": [
      "name1",
      "name2"
    ]
}
]

However I am having problem displaying them in an html table from my jsp. I tried:

<c:forEach begin="0" end="${userList.length() -1}" var="i">
<tr>
     <td>${userList.getJSONObject(i).get("Name")}
      </td>
      <td>${userList.getJSONObject(i).get("Email")}
     </td>
    
</tr>
</c:forEach>

The table is created as : Name Email
["name1","name2"] ["[email protected]","[email protected]"]

Can someone tell me how to display the records in tabular format(the values should be on each rows and not sidewide? Thanks in advance!


Solution

  • You'll need two nested c:forEach loops here, one to iterate over the outer userList array and the other to iterate over the inner Name and Email arrays.

    <c:forEach begin="0" end="${userList.length() - 1}" var="i">
        
        <c:set var="names" value='${userList.getJSONObject(i).get("Name")}' />
        <c:set var="emails" value='${userList.getJSONObject(i).get("Email")}' />
    
        <c:forEach begin="0" end="${names.length() - 1}" var="j">
        <tr>
            <td>${names.getString(j)}</td>
            <td>${emails.getString(j)}</td> 
        </tr>
        </c:forEach>
    
    </c:forEach>
    

    The example assumes that the Name and Email arrays will always contain the same number of items. If not, some kind of error handling would need to be put in place.