文件中添加 FastJSON 2 的依赖
发布时间:2025-06-24 18:40:27 作者:北方职教升学中心 阅读量:036
在 Spring Boot 3 中,默认的 JSON 处理器是 Jackson。
3. 使用 FastJSON2 进行 JSON 序列化和反序列化
在你身上 Spring Boot 在应用中c;可直接使用 FastJSON 的 API 进行 JSON 序列化和反序列化。
文件中添加 FastJSON 2 的依赖。import com.alibaba.fastjson2.support.config.FastJsonConfig;import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;import lombok.extern.slf4j.Slf4j;import org.springframework.context.annotation.Configuration;import org.springframework.http.MediaType;import org.springframework.http.converter.HttpMessageConverter;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import java.nio.charset.StandardCharsets;import java.util.Collections;import java.util.List;@Slf4j@Configurationpublic class Fastjson2Config implements WebMvcConfigurer { /** * Fastjson2Config * @author <a href="https://zhengkai.blog.csdn.net/">zhengkai.blog.csdn.net</a> */ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); FastJsonConfig config = new FastJsonConfig(); config.setDateFormat("yyyy-MM-dd HH:mm:ss"); // 其他配置... converter.setFastJsonConfig(config); converter.setDefaultCharset(StandardCharsets.UTF_8); converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON)); converters.add(0, converter); log.info("Fastjson2 Initial Done"); }}。SpringBoot3脚手架,基于SpringBoot3+Druid+PgSQL+Mybatisplus13#43;FastJSON2+Lombok,启动web容器为Undertow(非默认tomcat),请自行添加和配置其他内容。例如:
import com.alibaba.fastjson2.JSON;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class SampleController { @GetMapping("/json") public String getJson() { MyObject obj = new MyObject(); obj.setName("Test"); obj.setValue(123); // 使用 FastJSON 进行序列化 return JSON.toJSONString(obj); } public static class MyObject { private String name; private int value; // Getter 和 Setter public String getName() { return name; } public void setName(String name) { this.name = name; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } }}。。以下是详细的步骤:
1. 添加依赖。
4. 测试。
HttpMessageConverter。
4. 试验。
启动你的 Spring Boot 应用,并访问。以下是 Maven 依赖的示例:<!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2-extension-spring6 --><dependency> <groupId>com.alibaba.fastjson2</groupId> <artifactId>fastjson2-extension-spring6</artifactId> <version>2.0.53</version></dependency><!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 --><dependency> <groupId>com.alibaba.fastjson2</groupId> <artifactId>fastjson2</artifactId> <version>2.0.53</version></dependency>
2. 配置 FastJSON 作为 JSON 处理器。
在 Spring Boot 3 中整合 FastJSON 2 主要涉及以下步骤,包括添加依赖和配置 FastJSON 作为 JSON 处理器等。
3. 使用 FastJSON2 进行 JSON 序列化和反序列化。
首先,你需要你的。
开源项目。
路径,你应该能看到 FastJSON 生成的 JSON 响应。假如你想用 FastJSON 作为 JSON 处理器,您需要创建一个注册配置类别 FastJSON 的。 pom.xml。