springboot系列文章(四)-springboot使用fastjson

在spring boot中,如果在controller中加入了@ResponseBody,就会使用相应的httpmessageconverter来进行响应内容的处理,boot中默认使用jackson来响应数据的,公司项目中大多使用的是温少温高铁的fastjson,所以考虑如何来使用fastjson。

在boot中如果使用默认的jackson来解析数据,返回一个VO对象,就会出现一个问题,假如我要返回的是个user对象,如下:

public class User {

    private Long id;
    private String name;
    private Boolean sex;
    private Date created;

    public Long getId() {
        return id;
    }

    public User setId(Long id) {
        this.id = id;
        return this;
    }

    public String getName() {
        return name;
    }

    public User setName(String name) {
        this.name = name;
        return this;
    }

    public Boolean getSex() {
        return sex;
    }

    public User setSex(Boolean sex) {
        this.sex = sex;
        return this;
    }

    public Date getCreated() {
        return created;
    }

    public User setCreated(Date created) {
        this.created = created;
        return this;
    }
}

controller如下

@GetMapping("/user")
    @ResponseBody
    public Object user(String api_name) {
        User user = new User().setId(111111L).setSex(false).setCreated(new Date());
        return user;
    }


由于我没有给name设定值,那么返回的数据就会变成这样:

{
    id: 111111,
    name: null,
    sex: false,
    created: 1505985922932
}

name,会塞入null值

下面来讲讲换fastjson

首先,加入依赖

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.28</version>
		</dependency>

然后在启动类中,注入bean

	@Bean
	public HttpMessageConverters fastJsonHttpMessageConverters() {
		FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
		fastConverter.setFastJsonConfig(fastJsonConfig);
		HttpMessageConverter<?> converter = fastConverter;
		return new HttpMessageConverters(converter);
	}

这样,重新启动就会发现,name字段没有返回了,说明换成功了。

{
	created: 1506049561787,
	id: 111111,
	sex: false
}

总结,其实实现换fastjson的配置方式有很多,可以参考其他的文章,但是我选择这种方式来配置,是为了代码清晰,后面维护方便。

上面,我们已经使用了fastjson来替代jackson json来解析json数据,所以可以在项目中去掉jackson依赖。

boot中默认jackson依赖,是通过spring-boot-starter-web来传递性依赖jacson的

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

exclusion出去jackson的依赖即可


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值