SpringBoot返回JSON
1、SpringBoot返回JSON简介
随着web开发前后端分离技术的盛行,json是目前主流的前后端数据交互方式,使用json数据进行交互需要对json数据进行转换解析,需要用到一些json处理器,常用的json处理器有:
- jackson-databind,SpringBoot默认的json处理器
- Gson,是Google的一个开源框架
- fastjson,目前解析速度最快的开源解析框架,由阿里开发
下面分别介绍如何在SpringBoot中整合三大json解析框架。
2、整合jackson-databind
Jackson-databind是SpringBoot默认集成在web依赖中的框架,因此我们只需要引入spring-boot-starter-web依赖,就可以返回json数据:
接着上篇文章中的demo继续修改demo,先看下代码框架:

下面开始修改demo,返回json数据,首先在pojo下创建一个Good实体类,并且可以通过注解来解决日期格式等需求:
package com.gongsir.springboot02.pojo;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.Date;
public class Good {
private Integer id;
private String name;
@JsonIgnore
private Double price;
@JsonFormat(pattern = "yy-MM-dd")
private Date dealDate;
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 Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Date getDealDate() {
return dealDate;
}
public void setDealDate(Date dealDate) {
this.dealDate = dealDate;
}
}
然后在controller包下创建一个GoodController,在方法上加上@ResponseBody注解(也可以直接使用@RestController注解整个类)即可返回json信息:
@Controller
@RequestMapping(value = "/good")
public class GoodController {
@GetMapping(path = "/get")
@ResponseBody
public Good getGood(){
Good good = new Good();
good.setId(1);
good.setName("MacBook Pro 2019");
good.setPrice(16999.99);
good.setDealDate(new Date());
return good;
}
}
此时可以使用浏览器或者postman工具来查看结果,运行项目,调用http://localhost:8080/good/get接口:

3、整合Gson
使用Gson需要将SpringBoot默认依赖的jackson-databind除去,然后引入Gson:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!--除去jackson-databind依赖-->
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--引入Gson依赖-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
创建一个gson配置:
package com.gongsir.springboot02.configuration;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import java.lang.reflect.Modifier;
@Configuration
public class GsonConfig {
@Bean
GsonHttpMessageConverter gsonHttpMessageConverter(){
GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
GsonBuilder builder = new GsonBuilder();
//设置解析的日期格式
builder.setDateFormat("yyyy-MM-dd");
//设置忽略字段,忽略修饰符为protected的字段属性
builder.excludeFieldsWithModifiers(Modifier.PROTECTED);
Gson gson = builder.create();
gsonHttpMessageConverter.setGson(gson);
return gsonHttpMessageConverter;
}
}
修改Good,java:
package com.gongsir.springboot02.pojo;
import java.util.Date;
public class Good {
protected Integer id;
private String name;
private Double price;
private Date dealDate;
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 Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Date getDealDate() {
return dealDate;
}
public void setDealDate(Date dealDate) {
this.dealDate = dealDate;
}
}
启动项目,再次访问http://localhost:8080/good/get接口:

4、整合fastjson
引入fastjson依赖,修改刚刚的pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!--除去jackson-databind依赖-->
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--引入fastjson依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
配置fastjson有两种方法,方法一:自定义MyFastjsonConfig,提供FastJsonHttpMessageConverter Bean:
package com.gongsir.springboot02.configuration;
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.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class MyFastjsonConfig {
@Bean
FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
//升级之后的fastjson(1.2.28之后的版本)需要手动配置MediaType,否则会报错
List<MediaType> supportedMediaTypes = new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
supportedMediaTypes.add(MediaType.APPLICATION_PDF);
supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XML);
supportedMediaTypes.add(MediaType.IMAGE_GIF);
supportedMediaTypes.add(MediaType.IMAGE_JPEG);
supportedMediaTypes.add(MediaType.IMAGE_PNG);
supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
supportedMediaTypes.add(MediaType.TEXT_HTML);
supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
supportedMediaTypes.add(MediaType.TEXT_PLAIN);
supportedMediaTypes.add(MediaType.TEXT_XML);
converter.setSupportedMediaTypes(supportedMediaTypes);
config.setDateFormat("yyyy-MM-dd");
config.setCharset(Charset.forName("UTF-8"));
config.setSerializerFeatures(
//json格式化
SerializerFeature.PrettyFormat,
//输出value为null的数据
SerializerFeature.WriteMapNullValue
);
converter.setFastJsonConfig(config);
return converter;
}
}
方法二:实现WebMvcConfigurer接口,重写configureMessageConverters方法:
package com.gongsir.springboot02.configuration;
import com.alibaba.fastjson.serializer.SerializerFeature;
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.WebMvcConfigurer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class FastJsonConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
com.alibaba.fastjson.support.config.FastJsonConfig config = new com.alibaba.fastjson.support.config.FastJsonConfig();
//升级之后的fastjson(1.2.28之后的版本)需要手动配置MediaType,否则会报错
List<MediaType> supportedMediaTypes = new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
supportedMediaTypes.add(MediaType.APPLICATION_PDF);
supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XML);
supportedMediaTypes.add(MediaType.IMAGE_GIF);
supportedMediaTypes.add(MediaType.IMAGE_JPEG);
supportedMediaTypes.add(MediaType.IMAGE_PNG);
supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
supportedMediaTypes.add(MediaType.TEXT_HTML);
supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
supportedMediaTypes.add(MediaType.TEXT_PLAIN);
supportedMediaTypes.add(MediaType.TEXT_XML);
converter.setSupportedMediaTypes(supportedMediaTypes);
config.setDateFormat("yyyy-MM-dd");
config.setCharset(Charset.forName("UTF-8"));
config.setSerializerFeatures(
//json格式化
SerializerFeature.PrettyFormat,
//输出value为null的数据
SerializerFeature.WriteMapNullValue
);
converter.setFastJsonConfig(config);
//将converter加入到converters
converters.add(converter);
}
}
启动项目,再次调用接口:

SpringBoot返回JSON的更多相关文章
- springboot - 返回JSON error 从自定义的 ErrorController
使用AbstractErrorController(是ErrorController的实现),返回json error. 1.概览 2.基于<springboot - 映射 /error 到自定 ...
- springboot 返回json字符串格式化问题
在idea中yml文件中添加以下注解就可以格式化json字符串效果 spring: jackson: serialization: indent-output: true 原返回json格式为: {& ...
- [转] SpringBoot返回json 数据以及数据封装
作者:武哥 来源:武哥聊编程 https://mp.weixin.qq.com/s/QZk0sKxBX4QZiCTHQIA6pg 1. Spring Boot关于Json的知识点 在项目开 ...
- SpringBoot返回json和xml
有些情况接口需要返回的是xml数据,在springboot中并不需要每次都转换一下数据格式,只需做一些微调整即可. 新建一个springboot项目,加入依赖jackson-dataformat-xm ...
- SpringBoot 返回json 字符串(jackson 及 fast json)
一.jackson 1.Controller 类加注解@RestController 这个注解相当于@Controller 这个注解加 @ResponseBody 2.springBoot 默认使 ...
- SpringBoot 返回Json实体类属性大小写问题
今天碰到的问题,当时找了半天为啥前台传参后台却接收不到,原来是返回的时候返回小写,但是前台依旧大写传参. 查了很多后发现其实是json返回的时候把首字母变小写了,也就是Spring Boot中Jack ...
- SpringBoot返回JSON日期格式问题
SpringBoot中默认返回的日期格式类似于这样: "birth": 1537407384500 或者是这样: "createTime": "201 ...
- 【springBoot】springBoot返回json的一个问题
首先看下面的代码 @Controller @RequestMapping("/users") public class UserController { @RequestMappi ...
- SpringBoot返回json格式到浏览器上,出现乱码问题
在对应的Controller上的requestMapping中添加: @RestController@EnableAutoConfiguration@RequestMapping(value = &q ...
随机推荐
- POJ-1984-Navigation Nightmare+带权并查集(中级
传送门:Navigation Nightmare 参考:1:https://www.cnblogs.com/huangfeihome/archive/2012/09/07/2675123.html 参 ...
- CodeForces 340E Iahub and Permutations 错排dp
Iahub and Permutations 题解: 令 cnt1 为可以没有限制位的填充数字个数. 令 cnt2 为有限制位的填充数字个数. 那么:对于cnt1来说, 他的值是cnt1! 然后我们对 ...
- 【Offer】[61] 【扑克牌中的顺子】
题目描述 思路分析 测试用例 Java代码 代码链接 题目描述 从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的.2~10 为数字本身,A为1, J为11, Q为12,K为13,而大 ...
- Fire Balls 09——修正游戏的BUG
版权申明: 本文原创首发于以下网站: 博客园『优梦创客』的空间:https://www.cnblogs.com/raymondking123 优梦创客的官方博客:https://91make.top ...
- Mac环境IntelliJ IDEA配置JDK提示The selected directory is not a valid home for JDK
笔者使用mac配置如下: 硬件环境:MacBook Pro 操作系统:MacOS Sierra 10.13.6 开发工具:IntelliJ IDEA 2016.x JDK版本:已有Open JDK 8 ...
- spring 事务配置方式以及事务的传播性、隔离级别
在前面的文章中总结了spring事务的5中配置方式,但是很多方式都不用而且当时的配置使用的所有参数都是默认的参数,这篇文章就看常用的两种事务配置方式并信息配置事务的传播性.隔离级别.以及超时等问题,废 ...
- tomcat 中无法添加项目等问题的解决方案
博客地址:http://www.moonxy.com 一.前言 今天新建了一个 maven 项目,添加程序文件之后,发现无法添加项目,然后修改配置,将应用添加到了 tomcat,启动时又报错,解决出现 ...
- mysql8.0版本忘记root密码
1.先关掉系统服务 net stop mysql 2.进入mysql安装目录的bin文件中,以管理员的方式运行cmd,然后输入如下命令,实现无密码登陆 mysqld --console --skip- ...
- [Advanced Python] 13 - "Decorator": syntactic sugar
单独一章复习:Python 函数装饰器,廖雪峰讲装饰器 基本概念 函数作为变量 从函数中返回函数 子函数写在外面貌似也可以,可这样就少了“封装性”. def greet(): return " ...
- MyBatis返给前端正确的时间格式
前台获取位时间戳,后端解决办法之一 问题描述:前端获取后台接口返回的数据,时间是long类型的时间戳而不是时间类型2019-09-25 17:07:32 项目: JAVA web 工具:eclipse ...