SpringBoot怎麼返回Json資料格式
一、@RestController 註解
在 Spring Boot 中的 Controller 中使用 @RestController 註解即可傳回 JSON 格式的資料。
@RestController
註解包含了 @Controller 和 @ResponseBody 註解。@ResponseBody
註解是將傳回的資料結構轉換為 JSON 格式。
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Controller @ResponseBody public @interface RestController { String value() default ""; }
二、Jackson
在 Spring Boot 中預設使用的 JSON 解析技術框架是 Jackson。
點開pom.xml 中的spring-boot-starter-web 依賴,可以看到spring-boot-starter-json 依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-json</artifactId> <version>2.0.3.RELEASE</version> <scope>compile</scope> </dependency>
再次點進去上面提到的spring- boot-starter-json 依賴,可以看到如下程式碼:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.6</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jdk8</artifactId> <version>2.9.6</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>2.9.6</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-parameter-names</artifactId> <version>2.9.6</version> <scope>compile</scope> </dependency>
到此為止,可以知道Spring Boot 中預設使用的JSON 解析框架是Jackson。
1、物件、List、Map 轉換為Json格式
建立實體類別:
public class User { private Long id; private String username; private String password; /* 省略get、set和带参构造方法 */ }
Controller 圖層
#import com.itcodai.course02.entity.User; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @RequestMapping("/json") public class JsonController { @RequestMapping("/user") public User getUser() { return new User(1, "倪升武", "123456"); //返回 {"id":1,"username":"倪升武","password":"123456"} } @RequestMapping("/list") public List<User> getUserList() { List<User> userList = new ArrayList<>(); User user1 = new User(1, "倪升武", "123456"); User user2 = new User(2, "达人课", "123456"); userList.add(user1); userList.add(user2); return userList; //返回 [{"id":1,"username":"倪升武","password":"123456"},{"id":2,"username":"达人课","password":"123456"}] } @RequestMapping("/map") public Map<String, Object> getMap() { Map<String, Object> map = new HashMap<>(3); User user = new User(1, "倪升武", "123456"); map.put("作者信息", user); map.put("博客地址", "http://blog.itcodai.com"); map.put("CSDN地址", "http://blog.csdn.net/eson_15"); map.put("粉丝数量", 4153); return map; //返回 {"作者信息":{"id":1,"username":"倪升武","password":"123456"},"CSDN地址":"http://blog.csdn.net/eson_15","粉丝数量":4153,"博客地址":"http://blog.itcodai.com"} } }
2、Jackson 的配置類別
在轉JSON 格式的時候將所有的null 轉換為“” 的配置
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import java.io.IOException; @Configuration public class JacksonConfig { @Bean @Primary @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build(); objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() { @Override public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(""); } }); return objectMapper; } } // 修改一下上面返回 Map 的接口,将几个值改成 null 测试一下: @RequestMapping("/map") public Map<String, Object> getMap() { Map<String, Object> map = new HashMap<>(3); User user = new User(1, "倪升武", null); map.put("作者信息", user); map.put("博客地址", "http://blog.itcodai.com"); map.put("CSDN地址", null); map.put("粉丝数量", 4153); return map; // 返回 {"作者信息":{"id":1,"username":"倪升武","password":""},"CSDN地址":"","粉丝数量":4153,"博客地址":"http://blog.itcodai.com"} // 可以看到 Jackson 已经将所有 null 字段转成空字符串了。 }
三、Fastjson
Fastjson是阿里巴巴開源的。
Jackson 和 fastjson 有哪些不同?
從擴充來看,fastjson 沒有 Jackson 靈活,從速度或上手難度來看,fastjson 可以考慮,它也比較方便。
fastjson 的依賴
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.35</version> </dependency>
Fastjson 設定類別
使用fastjson 時,對null 的處理和Jackson 有些不同,需要繼承WebMvcConfigurationSupport類,然後覆寫configureMessageConverters 方法。
在方法中,我們可以選擇要實作null 轉換的場景,程式碼如下:
import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; @Configuration public class fastJsonConfig extends WebMvcConfigurationSupport { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); FastJsonConfig config = new FastJsonConfig(); config.setDateFormat("yyyy-MM-dd"); config.setSerializerFeatures( // 保留 Map 空的字段 SerializerFeature.WriteMapNullValue, // 将 String 类型的 null 转成"" SerializerFeature.WriteNullStringAsEmpty, // 将 Number 类型的 null 转成 0 SerializerFeature.WriteNullNumberAsZero, // 将 List 类型的 null 转成 [] SerializerFeature.WriteNullListAsEmpty, // 将 Boolean 类型的 null 转成 false SerializerFeature.WriteNullBooleanAsFalse, // 生成的JSON格式化 SerializerFeature.PrettyFormat, // 避免循环引用 SerializerFeature.DisableCircularReferenceDetect); converter.setFastJsonConfig(config); converter.setDefaultCharset(Charset.forName("UTF-8")); List<MediaType> mediaTypeList = new ArrayList<>(); // 解决中文乱码问题,相当于在 Controller 上的 @RequestMapping 中加了个属性 produces = "application/json" mediaTypeList.add(MediaType.APPLICATION_JSON); converter.setSupportedMediaTypes(mediaTypeList); converters.add(converter); } }
四、封裝傳回的資料格式
除了要封裝資料之外,我們往往需要在傳回的JSON 中加入一些其他訊息,例如傳回狀態碼Code,傳回Msg 給呼叫者,呼叫者可以根據Code 或Msg 進行一些邏輯判斷。
統一的 JSON 結構中屬性包含資料、狀態碼、提示資訊即可。
public class JsonResult<T> { private T data; private String code; private String msg; /** * 若没有数据返回,默认状态码为 0,提示信息为“操作成功!” */ public JsonResult() { this.code = "0"; this.msg = "操作成功!"; } /** * 若没有数据返回,可以人为指定状态码和提示信息 * @param code * @param msg */ public JsonResult(String code, String msg) { this.code = code; this.msg = msg; } /** * 有数据返回时,状态码为 0,默认提示信息为“操作成功!” * @param data */ public JsonResult(T data) { this.data = data; this.code = "0"; this.msg = "操作成功!"; } /** * 有数据返回,状态码为 0,人为指定提示信息 * @param data * @param msg */ public JsonResult(T data, String msg) { this.data = data; this.code = "0"; this.msg = msg; } // 省略 get 和 set 方法 }
修改 Controller 中的傳回值類型,測試
@RestController @RequestMapping("/jsonresult") public class JsonResultController { @RequestMapping("/user") public JsonResult<User> getUser() { User user = new User(1, "倪升武", "123456"); return new JsonResult<>(user); // {"code":"0","data":{"id":1,"password":"123456","username":"倪升武"},"msg":"操作成功!"} } @RequestMapping("/list") public JsonResult<List> getUserList() { List<User> userList = new ArrayList<>(); User user1 = new User(1, "倪升武", "123456"); User user2 = new User(2, "达人课", "123456"); userList.add(user1); userList.add(user2); return new JsonResult<>(userList, "获取用户列表成功"); // {"code":"0","data":[{"id":1,"password":"123456","username":"倪升武"},{"id":2,"password":"123456","username":"达人课"}],"msg":"获取用户列表成功"} } @RequestMapping("/map") public JsonResult<Map> getMap() { Map<String, Object> map = new HashMap<>(3); User user = new User(1, "倪升武", null); map.put("作者信息", user); map.put("博客地址", "http://blog.itcodai.com"); map.put("CSDN地址", null); map.put("粉丝数量", 4153); return new JsonResult<>(map); // {"code":"0","data":{"作者信息":{"id":1,"password":"","username":"倪升武"},"CSDN地址":null,"粉丝数量":4153,"博客地址":"http://blog.itcodai.com"},"msg":"操作成功!"} } }
以上是SpringBoot怎麼返回Json資料格式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

golangWebSocket與JSON的結合:實現資料傳輸和解析在現代的Web開發中,即時資料傳輸變得越來越重要。 WebSocket是一種用於實現雙向通訊的協議,與傳統的HTTP請求-回應模型不同,WebSocket允許伺服器向客戶端主動推送資料。而JSON(JavaScriptObjectNotation)是一種用於資料交換的輕量級格式,它簡潔易讀

SpringBoot和SpringMVC都是Java開發中常用的框架,但它們之間有一些明顯的差異。本文將探究這兩個框架的特點和用途,並對它們的差異進行比較。首先,我們來了解一下SpringBoot。 SpringBoot是由Pivotal團隊開發的,它旨在簡化基於Spring框架的應用程式的建立和部署。它提供了一種快速、輕量級的方式來建立獨立的、可執行

MySQL5.7和MySQL8.0是兩個不同的MySQL資料庫版本,它們之間有以下一些主要差異:效能改進:MySQL8.0相對於MySQL5.7有一些效能改進。其中包括更好的查詢優化器、更有效率的查詢執行計劃產生、更好的索引演算法和平行查詢等。這些改進可以提高查詢效能和整體系統效能。 JSON支援:MySQL8.0引入了對JSON資料類型的原生支持,包括JSON資料的儲存、查詢和索引。這使得在MySQL中處理和操作JSON資料變得更加方便和有效率。事務特性:MySQL8.0引進了一些新的事務特性,如原子

PHP數組轉JSON的效能最佳化方法包括:使用JSON擴充和json_encode()函數;新增JSON_UNESCAPED_UNICODE選項以避免字元轉義;使用緩衝區提高循環編碼效能;快取JSON編碼結果;考慮使用第三方JSON編碼庫。

使用golang中的json.MarshalIndent函數將結構體轉換為格式化的JSON字串在使用Golang編寫程式時,我們經常需要將結構體轉換為JSON字串,在這個過程中,json.MarshalIndent函數可以幫助我們實現格式化的輸出。下面我們將詳細介紹如何使用這個函數,並提供具體的程式碼範例。首先,讓我們建立一個包含一些資料的結構體。以下是示

快速入門:Pandas讀取JSON檔案的方法,需要具體程式碼範例引言:在資料分析和資料科學領域,Pandas是一個重要的Python庫之一。它提供了豐富的功能和靈活的資料結構,能夠方便地對各種資料進行處理和分析。在實際應用中,我們經常會遇到需要讀取JSON檔案的情況。本文將介紹如何使用Pandas來讀取JSON文件,並附上特定的程式碼範例。一、Pandas的安裝

Jackson庫中的註解可控制JSON序列化和反序列化:序列化:@JsonIgnore:忽略屬性@JsonProperty:指定名稱@JsonGetter:使用獲取方法@JsonSetter:使用設定方法反序列化:@JsonIgnoreProperties:忽略屬性@ JsonProperty:指定名稱@JsonCreator:使用建構子@JsonDeserialize:自訂邏輯

使用PHP的json_encode()函數將陣列或物件轉換為JSON字串並格式化輸出,可以讓資料在不同的平台和語言之間進行傳遞和交換變得更加容易。本文將介紹json_encode()函數的基本用法,以及如何將JSON字串格式化輸出。一、json_encode()函數的基本用法json_encode()函數的基本語法如下:stringjson_encod
