spring-boot-json(第三篇)
本文介紹spring-boot返回json格式資料,通過fastjson轉化。
1、開發準備
Ø 開發環境jdk1.7或者1.8
Ø 開發工具Eeclipse
Ø 專案管理工具maven
2、建立工作空間
使用idea建立一個module, idea中module相當於eclipse中的專案,名稱為spring-boot-json.
建立成功後目錄如下:
3、 在pom.xml中引入spring-boot、fastjson的jar包
<?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>com.example.springboot</groupId> <artifactId>springboot-json</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot-json</name> <description>Demo project for Spring Boot</description> <!--專案基本屬性配置 註釋快捷鍵:Ctrl+shift+正斜槓 ; 格式化: Ctrl+Alt+L --> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <!-- 引入spring-boot父節點--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <!-- 引入spring-boot-web依賴包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 引入spring-boot-test測試包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- 引入json處理包 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.35</version> </dependency> </dependencies> <build> <finalName>springboot-json</finalName> <plugins> <!-- 引入spring tomcat外掛包 --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
4、編寫User實體類
package com.example.springboot.json.entity; import java.util.Date; public class User { private String id; private String userName; private String password;}
以上就不提供get/set方法
5、編寫Controller類
package com.example.springboot.json.controller; import com.example.springboot.json.entity.User; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Date; /** * 使用@RestController等價於@Controler @ResponseBody * * @author wangsh * @date 2018/5/4 23:53 */ @RestController public class FastJsonController { /** * 請求對映:http://localhost:8080/hello * * @return */ @RequestMapping("/hello") public String hello() { System.out.println("hello..........."); return "hello"; } /** * 請求對映:http://localhost:8080/getUser * * @return */ @RequestMapping("/getUser") public User getUser() { User user = new User(); user.setId("1111111"); user.setUserName("zhangsan"); user.setPassword("123"); user.setCreateTime(new Date()); return user; } }
6、編寫啟動類配置fastjosn
fastjson支援方式一:
Ø 啟動類繼承WebMvcConfigurerAdapter
Ø 覆蓋方法configureMessageConverters
package com.example.springboot.json; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.util.List; /** * 1.使用fastjson,需要繼承WebMvcConfigurerAdapter,覆蓋configureMessageConverters方法 * * @author Administrator * */ @SpringBootApplication public class SpringbootJsonApplication extends WebMvcConfigurerAdapter { public static void main(String[] args) { // 啟動spring容器 SpringApplication.run(App.class, args); } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); // 建立fastjson物件 //建立convert訊息轉換物件 FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); // 新增fastjosn配置資訊,設定是否需要格式化 FastJsonConfig confg = new FastJsonConfig(); confg.setSerializerFeatures(SerializerFeature.PrettyFormat); //新增配置資訊到訊息物件 converter.setFastJsonConfig(confg); converters.add(converter); } }
fastjson支援方式二:
Ø 通過bean注入一個訊息物件
package com.example.springboot.json; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.context.annotation.Bean; @SpringBootApplication public class SpringbootJsonApplication { public static void main(String[] args) { SpringApplication.run(SpringbootJsonApplication.class, args); } /** * 使用bean方式注入fastjson解析器 * * @return */ @Bean public HttpMessageConverters fastJsonHttpMessageConverters() { // 建立fastjson物件 FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); FastJsonConfig confg = new FastJsonConfig(); // 設定是否需要格式化 confg.setSerializerFeatures(SerializerFeature.PrettyFormat); converter.setFastJsonConfig(confg); return new HttpMessageConverters(converter); } }
7、啟動執行錯誤
Information:java: Errors occurred while compiling module 'springboot-json'Information:javac 7 was used to compile java sources
Information:2018/5/5 0:08 - Compilation completed with 1 error and 0 warnings in 4s 579ms
Error:java: 無效的源發行版: 1.8
以上錯誤表示jdk版本不對
解決辦法:
1、將pom.xml中基本屬性jdk版本配置改為1.7
2、修改專案jdk編譯版本
Ctrl+Alt+Shift+S 開啟專案配置如下:
3、修改專案module編譯jdk版本
4、修改部署jdk版本
5、修改專案編譯版本
Ctrl+Alt+S 開啟設定如下:,選擇file->setting->build->compiler->java compiler
8、fastjson啟動測試結果
未使用fastjson如下,時間是毫秒值。
修改實體類,通過增加json標示@JSONField(format="yyyy-MM-dd")
public class User { private String id; private String userName; private String password; @JSONField(format="yyyy-MM-dd") private Date createTime;}
重新啟動服務測試如下:
通過以上結果可以看出,時間已經轉化為yyyy-MM-dd格式。
相關推薦
spring-boot-json(第三篇)
本文介紹spring-boot返回json格式資料,通過fastjson轉化。1、開發準備Ø 開發環境jdk1.7或者1.8Ø 開發工具EeclipseØ 專案管理工具maven2、建立工作空間使用idea建立一個module, idea中module相當於eclips
spring cloud連載第三篇之Spring Cloud Netflix
1. Service Discovery: Eureka Server(服務發現:eureka伺服器) 1.1 依賴 1 <dependency> 2 <groupId>org.springframework.cloud</groupI
spring cloud連載第三篇補充之Zuul
由於Zuul的內容較多所以單獨列出一篇來講。全是乾貨,如果學到東西的,動動小手給點個推薦^_^ 謝謝! 1. Router and Filter: Zuul(路由和過濾:Zuul) 路由是微服務架構不缺少的一部分。例如“/”可能對映到web服務,“/api/users”對映到使用者管理服務,而“/api/s
【Spring Cloud】第三篇 Client Side Load Balancer | 負載均衡
Ribbon是一個負載均衡的客戶端,用來提高系統的處理能力,在之後的章節會講到Feign它已經包含Ribbon。 word & phrase load balancer 負載均衡器 s
spring boot 開發—第七篇使用JWT保證api介面安全
1、jwt簡介 JWT是一種用於雙方之間傳遞安全資訊的簡潔的、URL安全的表述性宣告規範。JWT作為一個開放的標準(RFC 7519),定義了一種簡潔的,自包含的方法用於通訊雙方之間以Json物件的形式安全的傳遞資訊。因為數字簽名的存在,這些資訊是可信的,JW
spring boot 開發—第八篇整合OAuth2保證api介面安全
1、 OAuth 概念 OAuth 是一個開放標準,允許使用者讓第三方應用訪問該使用者在某一網站上儲存的私密的資源(如照片,視訊,聯絡人列表),而不需要將使用者名稱和密碼提供給第三方應用。OAuth允許使用者提供一個令牌,而不是使用者名稱和密碼來訪問他
spring boot 開發—第十篇修改tomcat容器上下文根地址
1、上下文跟預設地址 預設情況下springboot中request.getServletContext().getRealPath 返回的是一個臨時資料夾的地址 2、檢視原始碼 通過檢視原始碼 位置在org.springframework.boot.co
spring boot 開發—第九篇整合websocket
1、websocket簡介 1.1、WebSocket 是什麼? WebSocket 是一種網路通訊協議。RFC6455 定義了它的通訊標準。 WebSocket 是 HTML5 開始提供的一種在單個 TCP 連線上進行全雙工通訊的協議。 1.2、為什麼
spring boot實戰(第十篇)Spring boot Bean載入原始碼分析
public static void invokeBeanFactoryPostProcessors( ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostPro
spring boot 開發—第五篇SpringDataJPA整合 Redis 實現快取
對druid專案進行改造,增加redis快取支援。 1、redis簡介 Redis 是完全開源免費的,遵守BSD協議,是一個高效能的key-value資料庫。 Redis 與其他 key - value 快取產品有以下三個特點: Redis支援資料
spring boot實戰(第八篇)上下文的建立
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors( BeanDefinitionRegistry registry, Object source) { DefaultListableBe
從.Net到Java學習第三篇——spring boot+mybatis+mysql
jar fig targe list pro ble TE png tween 環境:mysql5.7 新建mysql數據庫demo,然後執行如下sql腳本進行數據表創建和數據初始化: -- ---------------------------- -- Tabl
第三篇:Spring Boot整合MyBatis
本文主要講解如何在Spring Boot下整合MyBatis並訪問資料庫。MyBatis 是一款優秀的持久層框架,它支援定製化 SQL、儲存過程以及高階對映。(如不瞭解點選前往) 環境依賴 修改 POM 檔案,新增mybatis-spring-boot-starter依賴。值得注
微服務:Spring Boot第三篇——資料訪問Spring Data JPA
這篇要從HelloWorld進一步,實現從資料庫中取資料,然後顯示在web頁面上的功能,資料庫採用H2,這是一種嵌入式的資料庫,無需安裝獨立的客戶端或者伺服器端。 Hibernate是一種使用物件關係對映(Object-Relational Mapping)實現資料訪問和操作的技術,它將
104. Spring Boot 啟動流程分析第三篇【從零開始學Spring Boot】
問題的提出:Spring Boot不像spring需要定義xml檔案檔案,那麼spring boot是如何在沒有配置檔案的情況下為我們啟動一個完整的WEB工程的呢。我們先@SpringBootApplication開始分析下這個啟動流程,原始碼取自:1.4.1.RELEAS
spring boot實戰(第十二篇)整合RabbitMQ
this direct 還需要 添加屬性 創建 還需 topic start routing 前言 本篇主要講述Spring Boot與RabbitMQ的整合,內容非常簡單,純API的調用操作。 操作之間需要加入依賴Jar [html] view plain cop
spring boot實戰(第十四篇)整合RabbitMQ原始碼分析前言
public void afterPropertiesSet() { synchronized (this.lifecycleMonitor) { if (this.running || !this.autoStartup) { return; } if (this.con
spring boot實戰(第十一篇)初識RabbitMQ
package org.lkl.mq.rabbitmq.test; import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import
Spring Cloud系列教程 | 第三篇:Eureka心跳健康檢查機制
推薦 Spring Cloud 視訊: Eureka心跳健康檢查機制 執行階段執行健康檢查的目的是為了從Eureka伺服器登錄檔中識別並刪除不可訪問的微服務,Eureka 伺服器並不是向客戶端傳送心跳請求,而是反過來,Eureka 客戶端將心跳傳送到Eurek
Spring第二篇和第三篇的補充【JavaConfig配置、c名稱空間、裝載集合、JavaConfig與XML組合】
前言 在寫完Spring第二和第三篇後,去讀了Spring In Action這本書…發現有知識點要補充,知識點跨越了第二和第三篇,因此專門再開一篇博文來寫… 通過java程式碼配置bean 由於Spring的自動裝配並不能將第三方庫元件裝配到應用中,於是