SpringBoot - Jackson、Gson、fastJson返回JSON数据

一、Jackson

spring-boot-starter-web中默认加入了jackson-databind作为JSON处理器。在jackson中,对要忽略的属性上加@JsonIgnore即可,而对于时间进行格式化,则需要在需要格式化的属性上面加上@JsonFormat注解,并指定格式。

1、创建POJO类

@Data
public class Student {
    /** ID */
    private Long id;
    /** 姓名 */
    private String name;
    /** 性别 */
    private String sex;
    /** 班级 */
    @JsonIgnore  // 忽略传送给前端
    private String classGrade;
    /** 入学日期 */
    @JsonFormat(pattern = "yyyy-MM-dd")  // 时间格式化
    private Date admissionDate;
}

2、创建Controller层

@RestController
public class StudentController {
    @GetMapping("/student")
    public Student student(){
        Student student = new Student();
        student.setId(1L);
        student.setName("柳成荫");
        student.setSex("男");
        student.setClassGrade("21班");
        student.setAdmissionDate(new Date());
        return student;
    }
}

3、结果查看

JSON数据

二、Gson

gson是一个JSON的开源解析框架。在SpringBoot中要使用其他的JSON解析框架,因为spring-boot-starter-web自动引入了jackson-databind,所以需要先移除它。

1、pom依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <!-- 去除默认的jackson -->
    <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>

2、配置文件

在写配置文件前,先对之前的Student类进行修改,去除所有属性上的注解,并将Sex属性修改为protected,这是因为Gson可以指定被某类修饰符所修饰的属性进行忽略。
SpringBoot使用Gson可以像jackson一样,因为提供了自动转换类。但是想要对日期进行格式化,需要自己提供自定义的HttpMessagerConverter

@Configuration
public class GsonConfig {
    @Bean
    public GsonHttpMessageConverter gsonHttpMessageConverter(){
        GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
        GsonBuilder builder = new GsonBuilder();
        // 设置解析日期的格式
        builder.setDateFormat("yyyy-MM-dd HH:MM:SS");
        // 过滤修饰符为protected的属性
        builder.excludeFieldsWithModifiers(Modifier.PROTECTED);
        Gson gson = builder.create();
        converter.setGson(gson);
        return converter;
    }
}

3、结果查看

JSON

三、fastJson

fastjson是阿里巴巴的一个开源JSON解析框架,是目前JSON解析速度最快的开源框架。同样,集成fastjson需要去除默认的jacksonfastjson不能像前面两个框架,在SpringBoot中可以直接使用,它需要我们自己提供一个HttpMessageConverter

1、pom依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <!-- 去除默认的jackson -->
    <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.28</version>
</dependency>

2、配置文件

fastjson可以自己写一个config,像上面的gson一样,提供FastJsonHttpMessageConverter的方法即可,也可以通过实现WebConfigurer接口里的configureMessageConverters方法来进行配置。

@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,        // 在生成JSON中输出类名(一般都不需要)
                SerializerFeature.WriteMapNullValue,     // 输出value为null的数据
                SerializerFeature.PrettyFormat,          // JSON格式化
                SerializerFeature.WriteNullListAsEmpty,  // 集合为空时,输出[]
                SerializerFeature.WriteNullStringAsEmpty // String为空时,输出""
        );
        converter.setFastJsonConfig(config);
        // 将自定义的FastJsonHttpMessageConvert加入converters中
        converters.add(converter);
    }
}

前面说了,可以通过自己写的配置类来完成FastJsonHttpMessageConverter

@Configuration
public class MyFastJsonConfig {
	@Bean
	public FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){
		// 将上面方法里的内容写到这里即可
	}
}

其实Gson也是可以通过WebMvcConfigurer接口来做,但是不推荐。因为,如果项目中没有GsonHttpMessageConverter,SpringBoot会自己提供一个GsonHttpMessageConverter。这时,我们去重写configureMessageConverters方法需要替换已有的GsonHttpMessageConverter实例,这是很麻烦的。

3、yml配置文件

使用fastjson,还需要配置响应编码,如果不配置,可能会导致中文乱码。

spring:
  http:
    encoding:
      force-response: true       # 响应编码

4、结果查看

JSON

发布了100 篇原创文章 · 获赞 25 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_40885085/article/details/105182508
今日推荐