Home > database >  Iterating through JSON object in Thymeleaf
Iterating through JSON object in Thymeleaf

Time:11-25

I am a bit stuck in one of the issue lately. I am using thymeleaf to render the html after getting the response. We have a complex JSON which looks like below

{
    "lastMonth": 11,
    "firstMonth": 9,
    "reportData": {
        "123456": {
            "usageByMonth": {
                "9": 233,
                "10": 233,
                "11": 218
            },
            "company": "Some Company"
        },
        6768592": {
            "usageByMonth": {
                "9": 5,
                "10": 5,
                "11": 5
            },
            "companyName": "another company name"
        }
    }
}

I want to show these values for each report data in a html table. I set the context like below.

 val reports = repservice.fetchReport(stringy)
 val context = Context()
 context.setVariable("report", report)

Since, I am not very good at frontend/thymeleaf I am a bit confused on How I can iterate through this. For example what I am trying to create is a table which looks like this.

|Company|FirstMonth|LastMonth|
|Some Company|233|218|
|another company name|5|5|

Your suggestions and answers will be highly appreciated.

Note: If you think the question is a bit confusing, please comment on it, I will make it more clear.

Thank you !

CodePudding user response:

First of all, the context should be set like this:

context.setVariable("reports", reports)

The table example at www.thymeleaf.org includes iteration. I don't know how your variable reports looks like after parsing the JSON. But from the JSON, something similar to the following might work:

<table>
  <thead>
    <tr>
      <th>Company</th>
      <th>FirstMonth</th>
      <th>LastMonth</th>
    </tr>
  </thead>
  <tbody>
    <tr th:each="key: ${report["reportData"].keys}">
      <td th:text="${reportData[key]["companyName"]}"></td>
      <td th:text="${reportData[key]["usageByMonth"][report["firstMonth"].toString()]}"></td>
      <td th:text="${reportData[key]["usageByMonth"][report["lastMonth"].toString()]}"></td>
    </tr>
  </tbody>
</table>

CodePudding user response:

Well, after a bit of researching and trying. I found a answer. So thymeleaf can be iteratable with Java hashmaps. Forexample. If you want to iterate through the JSON above in the question. What we can do is the following.

<table>
 <thead>
      <tr>
        <th>
          Kunde
        </th>
        <th>FirstMonth</th>
        <th>LastMonth</th>
      </tr>
      </thead>
<tbody>
      <tr th:each="reporting: ${report.reportData}">
          <td th:text="${reporting.value.companyName}"></td>
          <td  th:text="${reporting.value.usageByMonth[report.firstMonth]}"></td>
          <td  th:text="${reporting.value.usageByMonth[report.lastMonth]}"></td>
      </tr>

</table>

With that, I got what I needed. If you also face a similar issue, please don't hesitate to ask. :)

  • Related