Spring Boot集合转换JSON
示例【Spring Boot集合转换JSON】
程序清单:/springboot2/src/main/resources/templates/index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Boot转换集合数据</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}">
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}"/>
<script type="text/javascript" th:src="@{js/jquery-1.11.0.min.js}"></script>
<script type="text/javascript" th:src="@{js/bootstrap.min.js}"></script>
<script type="text/javascript">
$(document).ready(function(){
findBooks();
});
function findBooks(){
$.post("/findUsers",null,
function(data){
$.each(data,function(){
var tr = $("<tr/>");
$("<td/>").html(this.userName).appendTo(tr);
$("<td/>").html(this.sex).appendTo(tr);
$("<td/>").html(this.age).appendTo(tr);
$("#userTable").append(tr);
})
},"json");
}
</script>
</head>
<body>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Spring Boot转换集合数据</h3>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4">
<table class="table table-bordered" id="userTable">
<thead>
<tr>
<th>用户名</th>
<th>性别</th>
<th>年龄</th>
</tr>
</thead>
<tbody class="text-center"></tbody>
</table>
</div>
</div>
</div>
</body>
</html>
程序清单:/springboot2/src/main/java/com/dwx/hello/UserController.java
package com.dwx.hello;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@RequestMapping("/findUsers")
public List<User> findUsers() {
List<User> users=new ArrayList<>();
users.add(new User("jack","男",22));
users.add(new User("lucy","女",18));
users.add(new User("tom","男",20));
return users;
}
}
启动Spring Boot项目,访问如下地址:http://localhost:8080/