SpringBoot | 配置fastjson

两种方式配置fastjson

一、在启动类直接注入bean

   @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters(){
        //1. 需要定义一个converter转换消息的对象
        FastJsonHttpMessageConverter fasHttpMessageConverter = new FastJsonHttpMessageConverter();

        //2. 添加fastjson的配置信息,比如:是否需要格式化返回的json的数据
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);

        //3. 在converter中添加配置信息
        fasHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        return new HttpMessageConverters((HttpMessageConverter<?>) fasHttpMessageConverter);
    }
	

二、创建config类实现WebMvcConfigurer(springboot为2.0版本的)

package com.example.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaobu
 * @version JDK1.8.0_171
 * @date on  2019/1/14 12:46
 * @description V1.0
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {


    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter);
        converters.add(fastJsonHttpMessageConverter());
        System.out.println("converters = " + converters);
    }



    /**
     * fastJson相关设置
     */
    private FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
        fastJsonHttpMessageConverter.setFastJsonConfig(getFastJsonConfig());
        return fastJsonHttpMessageConverter;
    }

    /**
     * fastJson相关设置
     */
    private FastJsonConfig getFastJsonConfig() {
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        // 在serializerFeatureList中添加转换规则
        List<SerializerFeature> serializerFeatureList = new ArrayList<SerializerFeature>();
        serializerFeatureList.add(SerializerFeature.PrettyFormat);
        serializerFeatureList.add(SerializerFeature.WriteMapNullValue);
        serializerFeatureList.add(SerializerFeature.WriteNullStringAsEmpty);
        serializerFeatureList.add(SerializerFeature.WriteNullListAsEmpty);
        serializerFeatureList.add(SerializerFeature.DisableCircularReferenceDetect);
        SerializerFeature[] serializerFeatures = serializerFeatureList.toArray(new SerializerFeature[0]);
        fastJsonConfig.setSerializerFeatures(serializerFeatures);
        return fastJsonConfig;
    }


}

三、测试

新建个pojo类

package com.example.entity;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * @author xiaobu
 * @version JDK1.8.0_171
 * @date on  2019/2/14 10:09
 * @description V1.0
 */

@Data
public class FastJson {

    private int id;

    private String name;

    @JSONField(format = "yyyy-MM-dd hh:mm:ss")
    private LocalDateTime birthDate;
}

 

接着创建个控制器类

package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.example.entity.FastJson;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * @author xiaobu
 * @version JDK1.8.0_171
 * @date on  2019/2/14 9:59
 * @description V1.0 验证项目集成fastjson是否成功  观察下面的demo2方法表明fastjson配置生效了,默认是启用jackjson
 */

@RestController
@RequestMapping("fastJson")
public class FastJsonController {

    @GetMapping("demo2")
    public FastJson demo2(){
        FastJson fastJson = new FastJson();
        fastJson.setId(1);
        fastJson.setName("xiaobu");
        fastJson.setBirthDate(LocalDateTime.now());
        return  fastJson;
    }

    @GetMapping("demo3")
    public String demo3(){
        FastJson fastJson = new FastJson();
        fastJson.setId(1);
        fastJson.setName("xiaobu");
        fastJson.setBirthDate(LocalDateTime.now());
       return JSON.toJSONString(fastJson);
    }
}

结果:

 


参考:https://segmentfault.com/a/1190000015975405

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中使用Fastjson配置方法如下: 1. 添加Fastjson依赖 在pom.xml文件中添加Fastjson依赖: ``` <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency> ``` 2. 配置Fastjson 在Spring Boot的配置类中添加以下配置: ``` @Configuration public class FastjsonConfig { @Bean public HttpMessageConverters fastjsonHttpMessageConverters() { // 创建Fastjson消息转换器 FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); // 创建配置FastJsonConfig config = new FastJsonConfig(); // 配置序列化策略 config.setSerializerFeatures( SerializerFeature.WriteMapNullValue, // 输出空置字段 SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null SerializerFeature.WriteNullStringAsEmpty // 字符类型字段如果为null,输出为"",而不是null ); converter.setFastJsonConfig(config); HttpMessageConverter<?> converter1 = converter; return new HttpMessageConverters(converter1); } } ``` 3. 使用Fastjson 在Controller中使用Fastjson进行序列化和反序列化: ``` @RestController public class UserController { @PostMapping("/user") public User addUser(@RequestBody User user) { // ... return user; } @GetMapping("/user/{id}") public User getUser(@PathVariable Long id) { // ... return user; } } ``` 以上就是Spring Boot中使用Fastjson配置方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值