這是來自 Spring MVC 控制器的 JSONObject 串列。
List<JSONObject> jsonDataList =
[{"key1":"value1","key2":"value2","key3":"value3","key4":"value4"}, {"key1":"value1","key2":"value2","key3":"value3","key4":"value4"}]
如何使用 th:each 迭代 Thymeleaf 中的 JSONObject 串列?
下面的 HTML 檔案中的代碼:=>
<tr th:each="data: ${jsonDataList}">
<td align="center"><span th:text="${data.key1}"></span></td> // getting exception here
</tr>
獲取例外為:引起:org.attoparser.ParseException:評估SpringEL運算式的例外:“data.key1”
uj5u.com熱心網友回復:
這是一種方法,但它做了一些假設:
a) 每個 JSON 物件具有相同數量的條目(否則您可能有一個參差不齊的表格,每行包含不同數量的單元格)。
b) 每個 JSON 物件具有相同順序的相同鍵(如果您希望表具有一致的列標題)。
此外,問題中的示例 JSON 假定所有值都是字串(value1
等等)。如果您的 JSON 值中有不同型別的物件,那么您需要確保它們具有所需的字串表示形式(例如 using toString()
)。
該方法:
<table>
<tr>
<th:block th:each="heading : ${jsonDataList.get(0).names()}">
<th th:text="${heading}"></th>
</th:block>
</tr>
<tr th:each="item : ${jsonDataList}">
<th:block th:each="name : ${item.names()}">
<td th:text="${item.get(name)}"></td>
</th:block>
</tr>
</table>
第一<tr>
部分處理從串列中的第一個物件讀取 JSON 物件鍵:
${jsonDataList.get(0).names()}
最后<tr>
一部分類似,但使用鍵來查找它們的相關值:
${item.get(name)}
生成的 HTML 為您提供了一個簡單的表格:
<table>
<tr>
<th>key1</th>
<th>key2</th>
<th>key3</th>
<th>key4</th>
</tr>
<tr>
<td>value1</td>
<td>value2</td>
<td>value3</td>
<td>value4</td>
</tr>
<tr>
<td>value1</td>
<td>value2</td>
<td>value3</td>
<td>value4</td>
</tr>
</table>
參考:
該th:block
標記在此處記錄。
此處JSONObject
記錄了可用于的方法。
uj5u.com熱心網友回復:
這個怎么樣?
<tr th:each="data: ${jsonDataList}">
<td align="center"><span th:text="[[${data.key1}]]"></span></td>
</tr>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/470602.html
下一篇:我正在嘗試在我的SpringBoot應用程式中添加一個jsp頁面。我的問題是,每次我嘗試訪問該頁面時,我都會遇到以下問題: