SpringBoot处理JSON数据
SpringBoot内置了JSON解析功能,默认使用Jackson来自动完成
当Controller返回的是一个Java对象或者是List集合时,SpringBoot自动将其转换成JSON数据
一、新建项目
1.创建一个Maven项目,命名为SpringBoot_jsontest,按照Maven项目的规范,src/main下新建一个resources的文件夹,再在此文件夹下新建static以及template两个文件夹。
2.修改pom.xml文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.fkit</groupId>
<artifactId>jsontest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>jsontest</name>
<url>http://maven.apache.org</url>
<!--
spring-boot-starter-parent是Spring Boot的核心启动器,
包含了自动配置、日志和YAML等大量默认的配置,大大简化了我们的开发。
引入之后相关的starter引入就不需要添加version配置,
spring boot会自动选择最合适的版本进行添加。
-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- 添加spring-boot-starter-web模块依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 添加spring-boot-starter-thymeleaf模块依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
3.引入静态文件
二、创建实体类
Dog.java:
package com.ysh.jsontest.domain;
import java.io.Serializable;
public class Dog implements Serializable {
private Integer id;
private String name;
private String image;
private Double price;
private String owner;
public Dog() {
// TODO Auto-generated constructor stub
}
public Dog(Integer id, String name, String image, Double price, String owner) {
this.id = id;
this.name = name;
this.image = image;
this.price = price;
this.owner = owner;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
}
三、创建index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<title>Spring Boot自动转换JSON数据</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(){
findDog();
});
function findDog(){
$.ajax("/findDog",// 发送请求的URL字符串。
{
dataType : "json", // 预期服务器返回的数据类型。
type : "post", // 请求方式 POST或GET
contentType:"application/json", // 发送信息至服务器时的内容编码类型
// 发送到服务器的数据。该函数的作用是:系列化对象 ,系列化对象说白了就是把对象的类型转换为字符串类型
data:JSON.stringify({id : 1, name : "巴扎黑"}),
async: true , // 默认设置下,所有请求均为异步请求。如果设置为false,则发送同步请求
// 请求成功后的回调函数。
success :function(data){
console.log(data);
$("#image").attr("src","images/"+data.image+"");
$("#name").html(data.name);
$("#price").html(data.price);
$("#owner").html(data.owner);
},
// 请求出错时调用的函数
error:function(){
alert("数据发送失败");
}
});
}
</script>
</head>
<body>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Spring Boot中Java对象转换JSON</h3>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4">
<p>照片:<img id="image" src="images/1.jpg" width="60" height="60"/></p>
<p>名字:<span id="name"></span></p>
<p>价格:<span id="price"></span></p>
<p>主人:<span id="owner"></span></p>
</div>
</div>
</div>
</body>
</html>
四、创建AppController控制器
package com.ysh.jsontest.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class AppController {
@RequestMapping(value = "/index")
public String index() {
return "index";
}
@RequestMapping(value = "/getjson")
public String getjson() {
return "getjson";
}
}
五、创建DogController控制器
package com.ysh.jsontest.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ysh.jsontest.domain.Dog;
@RestController
public class DogController {
/**
* Spring Boot默认使用jackson框架解析jason
* */
@RequestMapping("/findDog")
public Dog findDog(@RequestBody Dog dog){
// 观察页面传入的json数据是否封装到Dog对象
System.out.println(dog);
// 设置dog其他信息
dog.setImage("2.jpg");
dog.setPrice(58.0);
dog.setOwner("badao");
return dog;
}
附:
findDog中的参数@RequestBody Dog dog 表示,使用@RequestBody注解获取页面传递的参数后,将JSON数据设置到对应的Book的属性中。
六、启动测试项目
项目启动后,在浏览器输入:http://localhost:8080/index
请求会提交到AppController类的index方法进行处理,传递JSON数据,该方法返回index字符串,即转到template/index.html中
七、启动测试SpringBoot转换集合数据
getjson.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<title>Spring Boot Web开发测试</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(){
findDogs();
});
function findDogs(){
$.post("/finddogs",null,
function(data){
$.each(data,function(){
var tr = $("<tr/>");
$("<img/>").attr("src","images/"+this.image).attr("height",60).attr("width",60).appendTo("<td/>").appendTo(tr);
$("<td/>").html(this.name).appendTo(tr);
$("<td/>").html(this.price).appendTo(tr);
$("#dogtable").append(tr);
})
},"json");
}
</script>
</head>
<body>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Spring Boot中集合转换JSON</h3>
</div>
</div>
<!-- .container 类用于固定宽度并支持响应式布局的容器。 -->
<div class="container">
<div class="col-md-12">
<div class="panel panel-primary">
<!-- .panel-heading 面板头信息。 -->
<div class="panel-heading">
<!-- .panel-title 面板标题。 -->
<h3 class="panel-title">图书信息列表</h3>
</div>
<div class="panel-body">
<!-- table-responsive:响应式表格,在一个表展示所有的数据,当不够显示的时候可以左右滑动浏览-->
<div class="table table-responsive">
<!--
.table 类可以为其赋予基本的样式 — 少量的内补(padding)和水平方向的分隔线。
.table-bordered 类为表格和其中的每个单元格增加边框。
.table-hover 类可以让 <tbody> 中的每一行对鼠标悬停状态作出响应。
-->
<table class="table table-bordered table-hover" id="dogtable">
<thead>
<tr>
<th class="text-center">照片</th >
<th class="text-center">名字</th>
<th class="text-center">价格</th >
</tr>
</thead>
<tbody class="text-center"></tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
附:
jQuery中选择器加尖括号的区别:
$("<img/>"):
https://blog.****.net/badao_liumang_qizhi/article/details/80987336
getjson.html页面使用jQuery发送请求,页面载入时调用findDogs函数,它会发送异步请求到“/finddogs”,请求成功后会返回一个JSON数据,包含多个狗狗信息,接着将返回的数据使用jQuery设置到页面的table表单当中。
八、向DogController控制器中加入代码
@RequestMapping("/finddogs")
public List<Dog> findBooks(){
// 创建集合
List<Dog> dogs = new ArrayList<Dog>();
// 添加狗对象
dogs.add(new Dog(1, "巴扎黑1", "1.jpg",109.00,"ysh"));
dogs.add(new Dog(2, "巴扎黑2", "2.jpg",108.00,"badao"));
dogs.add(new Dog(3, "巴扎黑3", "3.jpg",58.00,"liumang"));
dogs.add(new Dog(4, "巴扎黑4", "4.jpg",108.00,"qi"));
dogs.add(new Dog(5, "巴扎黑5", "5.jpg",79.00,"zhi"));
// 返回集合
return dogs;
}
springboot会将List数据转换成JSON格式后返回到客户端
九、测试返回的集合转换成JSON
运行APP:参照
https://blog.****.net/badao_liumang_qizhi/article/details/80948956
访问:http://localhost:8080/getjson
请求响应如图:
代码下载:
https://download.****.net/download/badao_liumang_qizhi/10533476