SpringBoot拾级而上·整合 Fastjson

一、添加Fastjson依赖

build.gradle文件dependencies中添加
最新版本可从这里获取
https://mvnrepository.com/artifact/com.alibaba/fastjson

compile group: 'com.alibaba', name: 'fastjson', version: '1.2.47'

二、创建一个配置管理类 WebConfig

package com.springboot.springboot_web.model;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;

@Configuration
public class WebConfig {

    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();

        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);

        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);

        HttpMessageConverter converter = fastJsonHttpMessageConverter;

        return new HttpMessageConverters(converter);

    }
}

三、测试类

1、创建一个实体类 User

public class User {

    private Integer id;
    private String username;
    private String password;
    private Date birthday;

    省略getter 和 setter方法
}

2、创建控制器类 FastjsonController

package com.springboot.springboot_web.control;

import com.springboot.springboot_web.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@RequestMapping("/fastjson")
public class FastjsonController {
    @RequestMapping("/test")
    @ResponseBody
    public User testJson() {
        User user = new User();

        user.setId(1);
        user.setUsername("jack");
        user.setPassword("jack123");
        user.setBirthday(new Date());

        return user;
    }
}

此时,打开浏览器,访问http://localhost:8081/fastjson/test,返回结果

{ "birthday":1533091223682, "id":1, "password":"jack123", "username":"jack" }

此时,还不能看出 Fastjson 是否正常工作,修改 User 类中使用 Fastjson 的注解,如下内容

@JSONField(format="yyyy-MM-dd")
private Date birthday;

再次访问http://localhost:8081/fastjson/test,返回结果
日期格式与我们修改的内容格式一致,说明 Fastjson 整合成功。

{ "birthday":"2018-08-01", "id":1, "password":"jack123", "username":"jack" }

你可能感兴趣的:(SpringBoot拾级而上·整合 Fastjson)