I got this class model (I made it only 2 column),
public class DataModel {
private int id;
private String name;
public DataModel() {}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
Here's the data.json,
[
{
"id":1,
"name":"Bill",
},
{
"id":2,
"name":"Steve",
}
]
Here's the controller class on the @PostConstruct(take 2-3 hours for figuring out the can't resolve json),
@PostConstruct
private void loadData() {
// load json
String strJson = null;
ClassPathResource classPathResource = new ClassPathResource("json/data.json");
try {
byte[] binaryData = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
strJson = new String(binaryData, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
// setup array mapper
ObjectMapper objectMapper = new ObjectMapper();
DataModel[] datawiz;
try {
datawiz = objectMapper.readValue(strJson, DataModel[].class);
// this print the first array on the json
System.out.println("Id = " + datawiz[0].getId() + " & Name = " + datawiz[0].getName());
} catch (Exception e) {
e.printStackTrace();
}
There's no problem there. How do I use it in thymeleaf html? I got only example like this,
// create menu list
DataModel menulist1 = new DataModel(1, "Bill");
DataModel menulist2 = new DataModel(2, "Steve");
// create the list
theData = new ArrayList<>();
add to the list
theData.add(menulist1);
theData.add(menulist2);
@GetMapping("/list")
public String listMenu(Model theModel) {
// add to the spring model
theModel.addAttribute("thelist", theData);
return "menu-list";
I can't do this theData=datawiz (of course removing those example with menulist* and .add).
Then on the menu-list.html,
<table>
<tbody>
<tr th:each="theList : ${thelist}">
<td th:text="${theList.id}" />
<td th:text="${theList.name}" />
</tr>
</tbody>
</table>
Tried this,
for(DataModel dataw : datawiz[]) {
theData.add(dataw);
}
didn't work.