You need to enable JavaScript to run this app. 求助:如何用Thymeleaf基于嵌套JSON生成指定结构的访客统计表格?
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何用Thymeleaf基于嵌套JSON生成指定结构的访客统计表格?

问题:无法根据JSON数据正确生成电影-地区访客统计多维表格

需要制作一个统计各电影在各地区的访客数量的层级表格:

  • 行标题:电影名
  • 列标题:按「国家-地区」层级展示
  • 单元格:对应电影在对应地区的访客数(无数据时填0)

目前遇到两个问题:

  1. 无法将访客数正确填充到对应的<td>标签,导致表格内容混乱
  2. 当前行标题的生成方式仅依赖第一个国家第一个地区的影院数据,存在数据不全的隐患

原始JSON数据

[
  {
    "country":"country 1",
    "districts":[
      {
        "district":"district 1",
        "cinemas":[
          {
            "cinema": "cinema 1",
            "movie":"Sherlock",
            "visitor":30
          },{
            "cinema": "cinema 2",
            "movie":"Terminator",
            "visitor":40
          },{
            "cinema": "cinema 2",
            "movie":"Tarzan",
            "visitor":20
          }]
      }, {
        "district":"district 2",
        "cinemas":[
          {
            "cinema": "cinema 1",
            "movie":"Sherlock",
            "visitor":12
          },{
            "cinema": "cinema 2",
            "movie":"Terminator",
            "visitor":41
          },{
            "cinema": "cinema 2",
            "movie":"Tarzan",
            "visitor":24
          }]
      }, {
        "district":"district 3",
        "cinemas":[
          {
            "cinema": "cinema 1",
            "movie":"Sherlock",
            "visitor":12
          },{
            "cinema": "cinema 2",
            "movie":"Terminator",
            "visitor":41
          }]
      }]
  }, {
    "country":"country 2",
    "districts":[
      {
        "district":"district 1",
        "cinemas":[
          {
            "cinema": "cinema 2",
            "movie":"Terminator",
            "visitor":40
          },{
            "cinema": "cinema 2",
            "movie":"Tarzan",
            "visitor":20
          }]
      }, {
        "district":"district 2",
        "cinemas":[
          {
            "cinema": "cinema 1",
            "movie":"Sherlock",
            "visitor":12
          },{
            "cinema": "cinema 2",
            "movie":"Tarzan",
            "visitor":24
          }]
      }, {
        "district":"district 3",
        "cinemas":[
          {
            "cinema": "cinema 1",
            "movie":"Sherlock",
            "visitor":12
          },{
            "cinema": "cinema 2",
            "movie":"Terminator",
            "visitor":41
          }]
      }]
  }
]

预期表格样式

---------------------------------------------------------------------------------------------------------
Movies     |country 1                                 | country 2                                       |
           ----------------------------------------------------------------------------------------------
           |district 1   | district 2  | district 3   | district 1    | district 2    | district 3      |
---------------------------------------------------------------------------------------------------------
Sherlock   | 30          | 12          | 12           | 0             | 12            | 12              |
Terminator | 40          | 41          | 41           | 40            | 0             | 41              |
Tarzan     | 20          | 24          | 0            | 20            | 24            | 0               |
---------------------------------------------------------------------------------------------------------

实际错误效果

表格中访客数被重复渲染,列数与预期不符,无法对应到正确的电影-地区组合,导致表格结构混乱。


现有代码

实体类

Country.java

public class Country {
    private String country;
    private List<District> districts;
    // 需添加getter/setter方法
}

District.java

public class District {
    private String district;
    private List<Cinema> cinemas;
    // 需添加getter/setter方法
}

Cinema.java

public class Cinema {
    String cinema;
    String movie;
    Integer visitor;
    // 需添加getter/setter方法
}

Controller代码

@GetMapping("/cinema")
public String getTable(Model model) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    File file = Paths.get(CINEMA_FILE_PATH).toFile();
    List<Country> countries = mapper.readValue(file, new TypeReference<List<Country>>() {});
    model.addAttribute("countries", countries);
    return "cinema";
}

Thymeleaf模板代码

<table>
  <thead>
  <tr>
    <th rowspan="2">Movies</th>
    <th th:each="country: ${countries}" th:colspan="${country.districts.size()}" th:text="${country.country}"></th>
  </tr>
  <tr>
    <th:block th:each="country: ${countries}">
        <th th:each="district:${country.districts}" th:text="${district.district}"></th>
    </th:block>
  </tr>
  </thead>
  <tbody>
    <tr th:each="cinema: ${countries.get(0).districts.get(0).cinemas}">
      <td th:text="${cinema.movie}"></td>
      <th:block th:each="country : ${countries}">
        <th:block th:each="district :${country.districts}">
            <td th:each="cinema :${district.cinemas}" th:text="${cinema.visitor}" />
        </th:block>
      </th:block>
    </tr>
  </tbody>
</table>

解决方案

1. 预处理数据(Controller层)

原始数据结构不适合直接渲染表格,需要先转换成「电影名 -> (国家-地区 -> 访客数)」的映射,同时收集所有唯一电影名:

@GetMapping("/cinema")
public String getTable(Model model) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    File file = Paths.get(CINEMA_FILE_PATH).toFile();
    List<Country> countries = mapper.readValue(file, new TypeReference<List<Country>>() {});

    // 收集所有唯一电影名
    Set<String> movieSet = new HashSet<>();
    // 构建电影-地区访客数映射:key=电影名,value=key=地区标识(国家-地区),value=访客数
    Map<String, Map<String, Integer>> movieVisitorMap = new HashMap<>();

    for (Country country : countries) {
        String countryName = country.getCountry();
        for (District district : country.getDistricts()) {
            String districtName = district.getDistrict();
            String areaKey = countryName + "-" + districtName;
            for (Cinema cinema : district.getCinemas()) {
                String movie = cinema.getMovie();
                movieSet.add(movie);
                // 初始化电影对应的映射
                movieVisitorMap.computeIfAbsent(movie, k -> new HashMap<>());
                // 存入访客数(如果同一地区同一电影有多个影院,这里求和,可按需调整)
                movieVisitorMap.get(movie).merge(areaKey, cinema.getVisitor(), Integer::sum);
            }
        }
    }

    // 转成有序列表
    List<String> movies = new ArrayList<>(movieSet);
    // 可选:对电影名排序
    Collections.sort(movies);

    model.addAttribute("countries", countries);
    model.addAttribute("movies", movies);
    model.addAttribute("movieVisitorMap", movieVisitorMap);

    return "cinema";
}

2. 修改Thymeleaf模板

基于预处理后的循环渲染,匹配电影名和地区获取对应访客数:

<table border="1" cellpadding="8" cellspacing="0">
  <thead>
    <tr>
      <th rowspan="2">Movies</th>
      <th th:each="country: ${countries}" th:colspan="${country.districts.size()}" th:text="${country.country}"></th>
    </tr>
    <tr>
      <th:block th:each="country: ${countries}">
        <th th:each="district:${country.districts}" th:text="${district.district}"></th>
      </th:block>
    </tr>
  </thead>
  <tbody>
    <tr th:each="movie : ${movies}">
      <td th:text="${movie}"></td>
      <th:block th:each="country : ${countries}">
        <th:block th:each="district :${country.districts}">
          <!-- 拼接地区标识,从映射中获取访客数,无数据则显示0 -->
          <td th:text="${movieVisitorMap.get(movie).getOrDefault(country.country + '-' + district.district, 0)}"></td>
        </th:block>
      </th:block>
    </tr>
  </tbody>
</table>

关键说明

  • 预处理数据时,将分散的影院数据聚合为电影-地区的访客数映射,避免前端复杂遍历匹配
  • 前端通过电影名和地区标识直接从映射中取值,确保每个单元格对应正确数据
  • 若同一地区同一电影有多个影院,代码中使用merge求和,可根据需求调整为取最大值/平均值等

内容的提问来源于stack exchange,提问作者Hg-lab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 03:21:31