4.1 返回JSON数据

发布于:2024-04-18 ⋅ 阅读:(161) ⋅ 点赞:(0)

1. 默认实现方式

JSON是目前主流的前后端数据传输方式,Spring MVC中使用消息转换器HttpMessageConverter对JSON的转换提供了很好的支持,在Spring Boot中更进一步,对相关配置做了更进一步的简化。
默认情况下,当开发者新创建一个Spring Boot项目后,添加Web依赖,代码如下:

        <!-- SpringBoot Web容器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

这个依赖中默认加入了jackson-databind作为JSON处理器,此时不需要添加额外的JSON处理器就能返回一段JSON了。
创建一个Book实体类:

public class Book {
	private String name;
	private String author;
	//JsonIgnore,忽略价格字段
	@JsonIgnore
	private Float price;
	@JsonFormat(pattern ="yyyy-MM-dd")
	private Date publicationDate;
	//省略getter/setter
}

然后创建BookController,返回Book对象即可:

@Controller
public class BookController {
	@GetMapping("/book")
	@ResponseBody
	public Book book(){
		Book book = new Book();
		book.setAuthor("罗贯中");
		book.setName("三国演义");
		book.setPrice(30f);
		book.setPublicationDate(new Date());
		return book;
	}
}

当然,如果需要频繁地用到@ResponseBody注解,那么可以采用@RestController组合注解代替@Controller和@ResponseBody,代码如下:

@RestController
public class BookController {
	@GetMapping("/book")
	public Book book(){
		Book book = new Book();
		book.setAuthor("罗贯中");
		book.setName("三国演义");
		book.setPrice(30f);
		book.setPublicationDate(new Date());
		return book;
	}
}

此时,在浏览器中输入“http://localhost:8080/book”,即可看到返回了JSON数据,如图4-1 所示。

在这里插入图片描述
这是SpringBoot自带的处理方式。如果采用这种方式,那么对于字段忽略、日期格式化等常见都需求通过注解来解决

这是通过Spring中默认提供的MappingJackson2HttpMessageConverter来实现的,当然开发者在这里也可以根据实际需求自定义JSON转换器。

2. 自定义转化器

常见的JSON处理器除了jackson-databind之外,还有Gson和fastson,这里针对常见用法分别举例。

1.使用Gson

Gson是Google的一个开源JSON解析框架。
使用Gson,需要先除去默认的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>

由于SpringBoot中默认提供了Gson的自动转换类GsonHttpMessageConvertersConfiguration,因此Gson的依赖添加成功后,可以像使用jackson-databind那样直接使用Gson。
但是在Gson进行转换时,如果想对日期数据进行格式化,那么还需要开发者自定义HttpMessageConverter
自定义HttpMessageConverter可以通过如下方式。
需要提供一个GsonHttpMessageConverter 即可,代码如下:

@Configuration
public class GsonConfig{
	@Bean
	GsonHttpMessageConverter gsonHttpMessageConverter(){
		GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
		GsonBuilder builder = new GsonBuilder();
		//设置Gson解析时日期的格式。
		builder.setDateFormat("yyyy-MM-dd");
		//设置Gson解析时修饰符为protected的字段被过滤掉
		builder.excludeFieldswithModifiers(Modifier.PROTECTED);
		Gson gson = builder.create();
		converter.setGson(gson);
		return converter;
	}
}

代码解释:

  • 开发者自己提供一个GsonHttpMessageConverter 的实例。
  • 设置Gson解析时日期的格式。
  • 设置Gson解析时修饰符为protected的字段被过滤掉。
  • 创建Gson对象放入GsonHttpMessageConverter的实例中并返回converter。

此时,将Book类中的price字段的修饰符改为protected,代码如下:

public class Book {
	private String name;
	private String author;
	protected Float price;
	private Date publicationDate;
	//省略getter/setter
}

最后,在浏览器中输入“http:/localhost:8080/book”,即可看到运行结果,如图4-2所示。
在这里插入图片描述

2.使用fastjson

fastson是阿里巴巴的一个开源JSON解析框架,是目前JSON解析速度最快的开源框架,该框架也可以集成到Spring Boot中。
不同于Gson,fastjson继承完成之后并不能立马使用,需要开发者提供相应的HttpMessageConverter后才能使用,集成fastjson的步骤如下。
首先除去jackson-databind依赖,引入fastjson依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
	<exclusions>
		<exclusion>
		<groupId>com,fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		</exclusion>
	</exclusions>
</dependency>
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.47</version>
</dependency>

然后配置fastjson的HttpMessageConverter:

@Configuration
public class MyFastJsonConfig {
	@Bean
	FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){
		FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
		FastJsonConfig config = new FastJsonConfig();
		config.setDateFormat("yyyy-MM-dd");
		config.setCharset(Charset.forName("UTF-8"));
		config.setSerializerFeatures(
		SerializerFeature.WriteClassName,
		SerializerFeature.WriteMapNullValue,SerializerFeature.PrettyFormat,
		SerializerFeature.WriteNullListAsEmpty,
		SerializerFeature.WriteNullstringAsEmpty
		);
		converter.setFastJsonConfig(config);
		return converter;
	}
}

代码解释:

  • 自定义MyFastJsonConfig,完成对FastJsonHtpMessageConverter Bean的提供。
  • 第7~15行分别配置了JSON解析过程的一些细节,例如日期格式、数据编码、是否在生成的JSON中输出类名、是否输出value为null的数据、生成的JSON格式化、空集合输出[]而非null、空字符串输出""而非null等基本配置。

MyFastJsonConfig配置完成后,还需要配置一下响应编码,否则返回的JSON中文会乱码,在application.properties中添加如下配置:

spring.http.encoding.force-response=true

接下来提供BookController进行测试。BookController和上一小节一致,运行成功后,在浏览器中输入“http://ocalhost:8080/book”,即可看到运行结果,如图4-3所示。
在这里插入图片描述
对于FastJsonHttpMessageConverter的配置,除了上面这种方式之外,

还有另一种方式。
在Spring Boot项目中,当开发者引入spring-boot-starter-web依赖之后,该依赖又依赖了spring-boot-autoconfigure,在这个自动化配置中,有一个WebMvcAutoConfiguration类提供了对SpringMVC最基本的配置,如果某一项自动化配置不满足开发需求,开发者可以针对该项自定义配置,只需要实现WebMvcConfigurer接口即可代码如下:

Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
		FastJsonHttpMessageConverter converter= new FastJsonHttpMessageConverter();
		FastJsonConfig config = new FastJsonConfig();
		config.setDateFormat("yyyy-MM-dd");
		config.setCharset(Charset.forName("UTF-8"));
		config.setSerializerFeatures(
			SerializerFeature.WriteClassName,
			SerializerFeature.WriteMapNullValue,
			SerializerFeature.PrettyFormat,
			SerializerFeature.WriteNullListAsEmpty,
			SerializerFeature.WriteNullStringAsEmpty
		);
		converter.setFastJsonConfig(config);
		converters.add(converter);
	}
}

代码解释:

  • 自定义MyWebMvcConfig类并实现WebMvcConfigurer接口中的configureMessageConverters方法
  • 将自定义的FastJsonHttpMessageConverter加入converters中。

网站公告

今日签到

点亮在社区的每一天
去签到