SpringBoot | 配置fastjson

本文详细介绍如何在SpringBoot项目中集成并配置Fastjson,包括直接在启动类注入bean和通过创建配置类实现的方式,同时提供了测试代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

两种方式配置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

### Spring Boot Kafka 使用 FastJSON 进行消息序列化 为了实现 Spring Boot 和 Kafka 的集成并使用 FastJSON 来处理消息的序列化和反序列化,可以按照如下方式配置: #### 配置依赖项 首先,在 `pom.xml` 文件中加入必要的 Maven 依赖来支持 Kafka 和 FastJSON。 ```xml <dependencies> <!-- Kafka --> <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> </dependency> <!-- Fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.83</version> </dependency> </dependencies> ``` #### 创建自定义序列化器与反序列化器类 接着创建两个 Java 类用于分别完成对象到 JSON 字符串以及相反过程的功能转换。 ```java import com.alibaba.fastjson.JSON; import org.apache.kafka.common.serialization.Deserializer; import java.nio.charset.StandardCharsets; public class FastJsonDeserializer<T> implements Deserializer<T> { private Class<T> typeClass; public void configure(Map<String, ?> configs, boolean isKey) {} @Override public T deserialize(String topic, byte[] data) { if (data == null || data.length == 0){ return null; } String jsonStr = new String(data, StandardCharsets.UTF_8); return JSON.parseObject(jsonStr, this.typeClass); } public void close() {} } ``` ```java import com.alibaba.fastjson.JSONObject; import org.apache.kafka.common.serialization.Serializer; import java.util.Map; public class FastJsonSerializer<T> implements Serializer<T> { @Override public void configure(Map<String, ?> configurations, boolean isKey) {} @Override public byte[] serialize(String topic, T data) { if (null == data) { return null; } else { JSONObject jsonObject = (JSONObject) JSONObject.toJSON(data); return jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8); } } @Override public void close() {} } ``` #### 修改 application.properties 或者 yml 中的相关设置 最后一步是在项目的配置文件里指定这些新的序列化工具给生产者和消费者使用。 对于 `application.yml`: ```yaml spring: kafka: consumer: key-deserializer: org.apache.kafka.common.serialization.StringDeserializer value-deserializer: com.example.FastJsonDeserializer # 替换成实际包名下的路径 producer: key-serializer: org.apache.kafka.common.serialization.StringSerializer value-serializer: com.example.FastJsonSerializer # 同上替换为具体位置 ``` 通过上述操作即可让 Spring Boot 应用程序中的 Kafka 组件能够利用 FastJSON 实现高效的消息体编码解码功能[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值