javascript
SpringBoot处理JSON数据
SpringBoot內(nèi)置了JSON解析功能,默認(rèn)使用Jackson來自動完成
當(dāng)Controller返回的是一個(gè)Java對象或者是List集合時(shí),SpringBoot自動將其轉(zhuǎn)換成JSON數(shù)據(jù)
一、新建項(xiàng)目
????? 1.創(chuàng)建一個(gè)Maven項(xiàng)目,命名為SpringBoot_jsontest,按照Maven項(xiàng)目的規(guī)范,src/main下新建一個(gè)resources的文件夾,再在此文件夾下新建static以及template兩個(gè)文件夾。
?????? 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等大量默認(rèn)的配置,大大簡化了我們的開發(fā)。
??引入之后相關(guān)的starter引入就不需要添加version配置,
???? spring boot會自動選擇最合適的版本進(jìn)行添加。
? -->
? <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.引入靜態(tài)文件
二、創(chuàng)建實(shí)體類
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;
?}
?
}
三、創(chuàng)建index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<title>Spring Boot自動轉(zhuǎn)換JSON數(shù)據(jù)</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",// 發(fā)送請求的URL字符串。
???{
???dataType : "json", // 預(yù)期服務(wù)器返回的數(shù)據(jù)類型。
?? ???type : "post", //? 請求方式 POST或GET
???? contentType:"application/json", //? 發(fā)送信息至服務(wù)器時(shí)的內(nèi)容編碼類型
???? // 發(fā)送到服務(wù)器的數(shù)據(jù)。該函數(shù)的作用是:系列化對象 ,系列化對象說白了就是把對象的類型轉(zhuǎn)換為字符串類型
???? data:JSON.stringify({id : 1, name : "巴扎黑"}),
???? async:? true , // 默認(rèn)設(shè)置下,所有請求均為異步請求。如果設(shè)置為false,則發(fā)送同步請求
???? // 請求成功后的回調(diào)函數(shù)。
???? success :function(data){
????? console.log(data);
???? $("#image").attr("src","images/"+data.image+"");
???? $("#name").html(data.name);
???? $("#price").html(data.price);
???? $("#owner").html(data.owner);
???? },
???? // 請求出錯(cuò)時(shí)調(diào)用的函數(shù)
???? error:function(){
????? alert("數(shù)據(jù)發(fā)送失敗");
???? }
?});
}
</script>
</head>
<body>
<div class="panel panel-primary">
?<div class="panel-heading">
??<h3 class="panel-title">Spring Boot中Java對象轉(zhuǎn)換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>價(jià)格:<span id="price"></span></p>
???<p>主人:<span id="owner"></span></p>
??</div>
?</div>
</div>
</body>
</html>
四、創(chuàng)建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";
? }
}
五、創(chuàng)建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默認(rèn)使用jackson框架解析jason
? * */
?@RequestMapping("/findDog")
?public Dog findDog(@RequestBody Dog dog){
??// 觀察頁面?zhèn)魅氲膉son數(shù)據(jù)是否封裝到Dog對象
??System.out.println(dog);
??// 設(shè)置dog其他信息
??dog.setImage("2.jpg");
??dog.setPrice(58.0);
??dog.setOwner("badao");
??return dog;
?}
附:
??? findDog中的參數(shù)@RequestBody? Dog dog 表示,使用@RequestBody注解獲取頁面?zhèn)鬟f的參數(shù)后,將JSON數(shù)據(jù)設(shè)置到對應(yīng)的Book的屬性中。
六、啟動測試項(xiàng)目
項(xiàng)目啟動后,在瀏覽器輸入:http://localhost:8080/index
請求會提交到AppController類的index方法進(jìn)行處理,傳遞JSON數(shù)據(jù),該方法返回index字符串,即轉(zhuǎn)到template/index.html中
七、啟動測試SpringBoot轉(zhuǎn)換集合數(shù)據(jù)
getjson.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<title>Spring Boot Web開發(fā)測試</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中集合轉(zhuǎn)換JSON</h3>
??</div>
?</div>
?<!-- .container 類用于固定寬度并支持響應(yīng)式布局的容器。 -->
?<div class="container">
??<div class="col-md-12">
???<div class="panel panel-primary">
????<!-- .panel-heading 面板頭信息。 -->??
????<div class="panel-heading">
?????<!-- .panel-title 面板標(biāo)題。 -->??
???? ?? <h3 class="panel-title">圖書信息列表</h3>
???? </div>
???? <div class="panel-body">
????<!-- table-responsive:響應(yīng)式表格,在一個(gè)表展示所有的數(shù)據(jù),當(dāng)不夠顯示的時(shí)候可以左右滑動瀏覽-->
????<div class="table table-responsive">
?????<!--
?????? .table 類可以為其賦予基本的樣式 — 少量的內(nèi)補(bǔ)(padding)和水平方向的分隔線。
???????????????? ?.table-bordered 類為表格和其中的每個(gè)單元格增加邊框。
???????????????? ?.table-hover 類可以讓 <tbody> 中的每一行對鼠標(biāo)懸停狀態(tài)作出響應(yīng)。
???????????????? -->
?????<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">價(jià)格</th >
???????</tr>
??????</thead>
??????<tbody class="text-center"></tbody>
?????</table>
????</div>
???</div>
???</div>
??</div>
?</div>
</body>
</html>
?
附:
jQuery中選擇器加尖括號的區(qū)別:
$("<img/>"):
https://blog.csdn.net/badao_liumang_qizhi/article/details/80987336
getjson.html頁面使用jQuery發(fā)送請求,頁面載入時(shí)調(diào)用findDogs函數(shù),它會發(fā)送異步請求到“/finddogs”,請求成功后會返回一個(gè)JSON數(shù)據(jù),包含多個(gè)狗狗信息,接著將返回的數(shù)據(jù)使用jQuery設(shè)置到頁面的table表單當(dāng)中。
?
八、向DogController控制器中加入代碼
?@RequestMapping("/finddogs")
?public List<Dog> findBooks(){
??// 創(chuàng)建集合
??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數(shù)據(jù)轉(zhuǎn)換成JSON格式后返回到客戶端
九、測試返回的集合轉(zhuǎn)換成JSON
運(yùn)行APP:參照
https://blog.csdn.net/badao_liumang_qizhi/article/details/80948956
訪問:http://localhost:8080/getjson
請求響應(yīng)如圖:
?
?
代碼下載:
https://download.csdn.net/download/badao_liumang_qizhi/10533476
與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的SpringBoot处理JSON数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jQuery中选择器加尖括号的区别
- 下一篇: SpringBoot实现注册时头像上传与