返回Json数据

1. 默认实现

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>net.minidev</groupId>
<artifactId>json-smart</artifactId>
<version>2.4.8</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.13.1</version>
</dependency>

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

@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
@ToString
public class Book{
	private string name;
    private String author;
    @JsonIgnore//一般标记在属性或者方法上,返回的json数据即不包含该属性
	private Float price;
    /*这里解释一下:@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
    pattern:是你需要转换的时间日期的格式
    timezone:是时间设置为东八区,避免时间在转换中有误差*/
	@JsonFormat (pattern = "yyyy-MM-dd" )	
    private Date publicationDate;
}
@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”,即可看到运行结果。

2. 自定义转换器

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

2.1 使用Gson

Gson是Google的一个开源JSON解析框架。使用Gson,需要先除去默认的jackson-databind,然后加入 Gson依赖,代码如下:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</ artifactId>
</dependency>dependency>
<exclusions>
<dependency>
<exclusion>
<groupId>com.fasterxml.jackson.core</ groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>

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

首先看GsonHttpMessageConvertersConfiguration中的一段源码:

@Bean
@ConditionalOnMissingBean
GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
	GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
	converter.setGson(gson);
	return converter;
}

@ConditionalOnMissingBean注解表示当项目中没有提供GsonHttpMessageConverter时才会使用默认的GsonHttpMessageConverter,所以开发者只需要提供一个GsonHttpMessageConverter即可,代码如下:

@Configuration
public class GsonConfig {
    @Bean
    GsonHttpMessageConverter gsonHttpMessageConverter() {
        GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
        GsonBuilder builder = new GsonBuilder();
        builder.setDateFormat("yyyy-MM-dd");
        builder.excludeFieldswithModifiers(Modifier.PROTECTED);
        Gson gson = builder.create();
        converter.setGson(gson);
        return converter;
    }
}

代码解释:

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

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

@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
@ToString
public class Book{
	private string name;
    private String author;
	protected Float price;
    private Date publicationDate;
}

最后,在浏览器中输入“http:/localhost:8080/book”,即可看到运行结果。

2.2 使用fastjson

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

首先除去 jackson-databind依赖,引入fastjson依赖:

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

然后配置fastjson的HttpMessageConverter:

@Configuration
public class MyFastJsonConfig {
    @Bean
    FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
        FastuJsonHttpMessageConverter 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,完成对FastJsonHttpMessageConverter Bean的提供。
  • 第7~15行分别配置了JSON解析过程的一些细节,例如日期格式、数据编码、是否在生成的JSON中输出类名、是否输出 value为null 的数据、生成的JSON格式化、空集合输出[]而非null、空字符串输出""而非null等基本配置。

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

spring.http.encoding.force-response=true

接下来提供BookController进行测试。BookController和上一小节一致,运行成功后,在浏览器中输入“http://localhost:8080/book”,即可看到运行结果。

对于FastJsonHttpMessageConverter的配置,除了上面这种方式之外,还有另一种方式。

在Spring Boot项目中,当开发者引入 spring-boot-starter-web 依赖之后,该依赖又依赖了spring-boot-autoconfigure,在这个自动化配置中,有一个 WebMvcAutoConfiguration类提供了对Spring MVC最基本的配置,如果某一项自动化配置不满足开发需求,开发者可以针对该项自定义配置,只需要实现 WebMvcConfigurer接口即可(在Spring 5.0之前是通过继承WebMvcConfigurerAdapter类来实现的),代码如下:

@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中。

**注意:**如果使用了Gson,也可以采用这种方式配置,但是不推荐。因为当项目中没有GsonHttpMessageConverter时,Spring Boot自己会提供一个GsonHtpMessageConverter,此时重写configureMessageConverters方法,参数converters中已经有GsonHttpMessageConverter的实例了,需要替换已有的GsonHttpMessageConverter实例,操作比较麻烦,所以对于Gson,推荐直接提供GsonHttpMessageConverter。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐