gson 如何在JSP中读取JSON并创建表

axr492tv  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(246)

我正在将下面的GSON JsonObject从servlet发送到JSP:-

{
    "TradesJSONArray": [{
        "SOURCE": "Trayport",
        "TRAN_NUM": 11884531,
        "EXCHANGETIME": "2022-07-28 12:30:56.0",
        "ERROR_DETAILS": "NULL"
    }, {
        "SOURCE": "Trayport",
        "TRAN_NUM": 11884532,
        "EXCHANGETIME": "2022-07-28 12:30:55.0",
        "ERROR_DETAILS": "NULL"
    }]
}

如何在JSP中读取或解析此JSON,以创建一个将Json键作为列名、将Json值作为列数据的表?
感谢并问候Saswata Mandal

p5cysglq

p5cysglq1#

我可以通过以下方式做到:

1) In Servlet :- 

  request.setAttribute("TradeJSON", jsonObj);   
  request.setAttribute("ResultSetColumnNames",etd.getResultSetColumnNames());

2) In JSP :- 

    <form name="tdform">    
        <div align="center">
            <table border="1" cellpadding="1">
                <caption><h2>Trade Details</h2></caption>
                <tr>
                <%
                   for(String column : (String[])request.getAttribute("ResultSetColumnNames"))
                   {
                %>
                    <th align="center"><%= column %></th>
                <% } %>                   
                </tr>
                <%                       
                 JsonObject jsonObj = (JsonObject)request.getAttribute("TradeJSON");
                 JsonArray jsonArry = jsonObj.getAsJsonArray("TradesJSONArray");
                 for (JsonElement je : jsonArry)
                 { 
                 %>
                 <tr>
                 <%
                    for (String columnName : (String[])request.getAttribute("ResultSetColumnNames"))
                    {
                    %>  
                    <td align="center"><%= je.getAsJsonObject().get(columnName).toString() %></td>
                    <%
                    }
                   %>
                   </tr>
                 <%
                 }  
                 %>
                </table>
        </form>

相关问题