Spring Boot系列(三):Spring Boot轉化為json資料格式
阿新 • • 發佈:2019-01-02
Spring Boot為我們良好的提供了我們需要的資料,將資料轉化為json格式,然後返回,
下面請看springboot轉化為json的方式;
第一種方式:
SpringBoot框架預設的方式;
步驟:
* 1.編寫實體類student;
package com.gmm; /**測試的實體類 * Created by john on 2017-04-30. */ public class Student { private Integer sId; private String sName; private String gender; public Integer getsId() { return sId; } public void setsId(Integer sId) { this.sId = sId; } public String getsName() { return sName; } public void setsName(String sName) { this.sName = sName; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }
* 2.編寫getStudernt()方法在controller中;
寫法:建立一個學生物件設定學生屬性資訊資料然後獲取以json的方式獲取這些資料;
package com.gmm; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by john on 2017-04-30.注意:*/ @RestController public class Controller { /** * springboot預設使用的json解析框架是jackson; * @return */ @RequestMapping("/getStudent") public Student getStudent(){ Student student = new Student(); student.setGender("女"); student.setsName("莉香"); student.setsId(1); return student; } }
@RestController 此註解是代表當前類是一個springboot應用程式;
@RequestMapping("/getStudent") 此註解是請求的對映路徑;
* 3.進行測試;
編寫一個Springboot的入口程式;
package com.gmm; import org.apache.log4j.Logger; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Created by john on 2017-04-30. */ @SpringBootApplication public class Application { private static Logger logger = Logger.getLogger(Application.class); public static void main(String[] args) { SpringApplication.run(Application.class,args); logger.info("=====spring boot start success===="); } }注:訪問路徑為http://localhost:8080/getStudent
谷歌遊覽器頁面顯示的結果為:
{"sId":1,"sName":"莉香","gender":"女"}
以上我們瞭解到SpringBootmoren 預設使用的json解析技術框架是jackson;
在maven下載的架包中可以看到有一個jackson.jar架包;
以上是第一種解析方式,通常我們也是用其它的解析方式;
第二種方式;
Spring Boot使用FastJson解析JSON資料
步驟
* 1.在上面pom,xml檔案依賴的基礎上新增FastJson的依賴包;
完整pom檔案
<?xml version="1.0" encoding="UTF-8"?> <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>springbootjson</groupId> <artifactId>com.gmm</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.1.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- 指定一下jdk的版本 ,這裡我們使用jdk 1.8 ,預設是1.6 --> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.15</version> </dependency> </dependencies> </project>在這個地方我們要強調一下,在官方文件說的1.2.10以後,會有兩個方法支援HttpMessageconvert,一個是FastJsonHttpMessageConverter,支援4.2以下的版本,一個是FastJsonHttpMessageConverter4支援4.2以上的版本,這裡也就是說:低版本的就不支援了,所以這裡最低要求就是1.2.10+。具體看文件!
* 2.配置fastjon(支援兩種方法);
第一種方法:
一:啟動類繼承extends WebMvcConfigurerAdapter
二:覆蓋方法configureMessageConverters
package com.gmm; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.apache.log4j.Logger; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.context.annotation.Bean; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.util.ArrayList; import java.util.List; /** springboot以fastjon方式轉化json資料; * Created by john on 2017-04-30. */ @SpringBootApplication public class Application extends WebMvcConfigurerAdapter { private static Logger logger = Logger.getLogger(Application.class); @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); //1.需要定義一個convert轉換訊息的物件; FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); //2.新增fastJson的配置資訊,比如:是否要格式化返回的json資料; FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //3處理中文亂碼問題 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); //4.在convert中新增配置資訊. fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes); fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); //5.將convert新增到converters當中. converters.add(fastJsonHttpMessageConverter); }public static void main(String[] args) { SpringApplication.run(Application.class,args); logger.info("=====spring boot start success===="); } }
三:在啟動測試實體類中新增一個屬性;並提供getset方法;
@JSONField(format = "yyyy-MM-dd HH:mm") private Date createTime; public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; }
@JSONField(format = "yyyy-MM-dd HH:mm")此註解是fastjon包提供的用於指定將資料返回什麼樣的json格式資料;四:在controller中在將新增的實體屬性給加進去;
@RequestMapping("/getStudent") public Student getStudent(){ Student student = new Student(); student.setGender("女"); student.setsName("莉香"); student.setsId(1); student.setCreateTime(new Date()); return student; }五:開啟springboot測試結果;
結果為:
說明springboot按照fastjson的方式將資料以json格式解析出來了;
第二種方法:
一:啟動測試類中注入Bean: HttpMessageConverters
具體做法:刪除繼承extends WebMvcConfigurerAdapter;
刪除重寫的方法改為以下程式碼;
@Bean public HttpMessageConverters fastJsonHttpMessageConverters(){ //1.需要定義一個convert轉換訊息的物件; FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); //2:新增fastJson的配置資訊; FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //3處理中文亂碼問題 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); //4.在convert中新增配置資訊. fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes); fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastJsonHttpMessageConverter; return new HttpMessageConverters(converter); }二:在入口springboot類中測試結果;
結果顯示和上面的結果是一樣的所有兩種方式都是有效的,具體使用哪種方法我感覺還是看你自己了!以上暫時結束!