如何在Thymeleaf中遍历复杂JSON对象并生成指定表格?
解决方案
先修正后端变量名问题
你当前代码存在变量名不一致的问题:
val reports = repservice.fetchReport(stringy) val context = Context() context.setVariable("report", report) // 此处变量名应为reports而非report
修正后代码:
val report = repservice.fetchReport(stringy) val context = Context() context.setVariable("report", report)
Thymeleaf前端实现代码
直接利用Thymeleaf的遍历语法处理reportData的Map结构,同时兼容公司名称字段不一致的情况,按指定月份提取用量数据:
<table border="1"> <thead> <tr> <th>Company</th> <th>FirstMonth</th> <th>LastMonth</th> </tr> </thead> <tbody> <!-- 遍历reportData下的所有公司详情对象 --> <tr th:each="item : ${report.reportData}"> <!-- 兼容company/companyName两种字段名 --> <td th:text="${item.company ?: item.companyName}"></td> <!-- 根据firstMonth对应的字符串键提取用量 --> <td th:text="${item.usageByMonth[#strings.toString(report.firstMonth)]}"></td> <!-- 根据lastMonth对应的字符串键提取用量 --> <td th:text="${item.usageByMonth[#strings.toString(report.lastMonth)]}"></td> </tr> </tbody> </table>
关键细节说明
th:each="item : ${report.reportData}":Thymeleaf会自动遍历Map的value集合,item即为每个公司的详情对象${item.company ?: item.companyName}:用Elvis运算符处理字段名不一致的情况,优先读取company字段,不存在则 fallback 到companyName#strings.toString(report.firstMonth):由于usageByMonth的键是字符串类型的月份(如"9"),而report.firstMonth是数字类型,需转换为字符串才能正确匹配取值
内容的提问来源于stack exchange,提问作者Farukh Khan
相关产品推荐
相关产品推荐

