Spring Boot集成fastjson2快速入门Demo

1.什么是fastjson2?

fastjson2是阿里巴巴开发的一个高性能的Java JSON处理库,它支持将Java对象转换成JSON格式,同时也支持将JSON字符串解析成Java对象。本文将介绍fastjson2的常见用法,包括JSON对象、JSON数组的创建、取值、遍历,以及与字符串、Java对象、Map、List的相互转换。

  • 支持JSON/JSONB两种协议,JSONPath 是一等公民。
  • 支持全量解析和部分解析。
  • 支持Java服务端、客户端Android、大数据场景。
  • 支持Kotlin
  • 支持JSON Schema alibaba.github.io/fastjson2/j...
  • 支持Android
  • 支持Graal Native-Image

2.代码工程

实验目标

在 Spring Web MVC 中集成 Fastjson2

pom.xml

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-demo</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>fastjson2</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.40</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2-extension-spring5</artifactId>
            <version>2.0.40</version>
        </dependency>
    </dependencies>
</project>

config

使用 FastJsonHttpMessageConverter 来替换 Spring MVC 默认的 HttpMessageConverter 以提高 @RestController@ResponseBody@RequestBody 注解的 JSON 序列化和反序列化速度。 配置示例如下:

java 复制代码
package com.et.fastjson2.config;
 

import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter;
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;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        //custom configuration
        FastJsonConfig config = new FastJsonConfig();
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        config.setReaderFeatures(JSONReader.Feature.FieldBased, JSONReader.Feature.SupportArrayToBean);
        config.setWriterFeatures(JSONWriter.Feature.WriteMapNullValue, JSONWriter.Feature.PrettyFormat);
        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(StandardCharsets.UTF_8);
        converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
        converters.add(0, converter);
    }
 
}

controller

typescript 复制代码
package com.et.fastjson2.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class HelloWorldController {
    @RequestMapping("/hello")
    public Map<String, Object> showHelloWorld(){
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "HelloWorld");
        return map;
    }
}

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

3.测试

4.fastjosn避坑

1.BigDecimal精度丢失问题

ini 复制代码
  @Test
    public void toJSONString() throws ParseException {
        UserDTO  user =  new UserDTO();
        BigDecimal money =new BigDecimal(-40090.07d);
        money = money.setScale(4, RoundingMode.HALF_UP);
        user.setMoney(money);

        String createtime ="2024-07-03 09:03:26.968";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date date = format.parse(createtime);
        user.setCreateTime(date);

        List<UserDTO> list = new ArrayList<>();
        list.add(user);
        String json=JSON.toJSONString(list);
        System.out.println(json);
    }

}

执行结果

css 复制代码
[{"createTime":"2024-07-03","money":-40090.700}]

发现没有一个怪异现象:-40090.07 变成了-40090.700,直接查几毛钱,原因是fastjson处理bigdecimal不是吧它当成字符串处理,导致丢失精度

解决方法

ini 复制代码
String json=JSON.toJSONString(list,  JSONWriter.Feature.WriteBigDecimalAsPlain);

2.日期解析问题

swift 复制代码
@Test
public void parseArray()  {
    String json="[{\"create_time\":\"2024-07-03 09:03:26.968\",\"money\":-40090.0700}]";
    System.out.println(json);
    List<UserDTO> list1 = JSON.parseArray(json, UserDTO.class,JSONReader.Feature.SupportSmartMatch);
    System.out.println();
}

运行结果

lua 复制代码
java.time.format.DateTimeParseException: Text '2024-07-03 09:03:26.968' could not be parsed, unparsed text found at index 10

解决方法

ini 复制代码
UserDTO上加上@JSONField(format= "yyyy-MM-dd HH:mm:ss")

5.引用

相关推荐
怒放de生命20104 小时前
IDEA 2025 最新版jrebel 破解
java·ide·intellij-idea
xiaodaidai丶5 小时前
Spring Web MVC的异步请求解读
spring boot·spring·mvc
MegaDataFlowers5 小时前
认识复杂度和简单排序算法
java·算法·排序算法
StackNoOverflow5 小时前
Maven 核心知识整理
java·maven
ekkcole5 小时前
easyexcel2.2.10版本对本地文件指定行或多行样式处理
java·easyexcel
小七mod5 小时前
【Nacos】Nacos1.4.x服务注册源码分析
java·spring cloud·微服务·nacos·源码·集群·注册中心
于先生吖5 小时前
Java 打车小程序 APP 源码 顺风车滴滴跑腿系统完整实现
java·开发语言·打车系统
凌冰_5 小时前
IDEA2025 基于 Jakarta EE 开发 Servlet + Thymeleaf
java·servlet
Mr.45675 小时前
SpringBoot整合RabbitMQ进阶:告别繁琐,用统一配置管理所有队列与交换机
spring boot·rabbitmq
会员源码网5 小时前
可变参数与数组混用导致的方法调用异常
java