(FREE)快速掌握阿里FastJSON:高效Java-JSON转换实战

一、参考文档

       阿里官方介绍: Quick Start CN · alibaba/fastjson Wiki

  1. 什么是什么是fastjson?

        官方:fastjson是阿里巴巴的开源JSON解析库,它可以解析JSON格式的字符串,支持将Java Bean序列化为JSON字符串,也可以从JSON字符串反序列化到JavaBean。

        通俗易懂版: fastjson是阿里推出的一款Java开源工具,专门用来处理JSON数据。它能快速地在Java对象和JSON格式之间互相转换,既能把对象变成JSON字符串,也能把JSON字符串变回对象。这个库最大的特点就是速度快、功能全、用起来简单,特别适合用在网站开发、数据交换和日志处理这些场景。

        2. fastjson的优点
  1.  fastjson相对其他JSON库的特点是快,从2011年fastjson发布1.1.x版本之后,其性能从未被其他Java实现的JSON库超越。

  2. 使用广泛fastjson在阿里巴巴大规模使用,在数万台服务器上部署,fastjson在业界被广泛接受。

  3. 测试完备fastjson有非常多的testcase,在1.2.11版本中,testcase超过3321个。每次发布都会进行回归测试,保证质量稳定。

  4. 使用简单fastjson的API十分简洁。

    // 序列化
    User user = new User("Alice", 25);
    String json = JSON.toJSONString(user, SerializerFeature.PrettyFormat);
    
    // 反序列化(复杂类型)
    String json = "{\"data\":[{\"name\":\"Alice\"}, {\"name\":\"Bob\"}]}";
    Result<List<User>> result = JSON.parseObject(json, 
        new TypeReference<Result<List<User>>>() {});
  5.  功能完备支持泛型,支持流处理超大文本,支持枚举,支持序列化和反序列化扩展。

        3.为什么选择使用fastjson?
fastjsonJacksonGsonorg.json
性能极高(序列化/反序列化速度最快)高(接近 Fastjson,流式 API 更快)中等(适合一般场景低(适合轻量级场景 )
易用性API 简介( 如 JSON.toJSONString配置灵活但稍复杂 ( 需熟悉 ObjectMapper )API 简单( 类似 Fastjson )功能简单,仅支持基础 JSON 操作
社区生态中文社区活跃,更新快国际社区成熟,插件丰富谷歌维护,稳定性高维护较少
适用场景高性能需求、复杂对象企业级应用、多语言兼容Android、简单场景轻量级 JSON 解析

二、使用案例

场景:MySQL数据库表数据导出json文件

工具:IDEA,MySQL

1.创建项目

选择maven架构,quickstart类型

2.导入JSON依赖

      <!-- MyBatis核心依赖 -->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
      </dependency>

      <!-- MySQL驱动 -->
      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.28</version>
      </dependency>

      <!-- Fastjson -->
      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.83</version>
      </dependency>

      <!-- 单元测试 -->
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
      </dependency>

3.连接数据库&生成类&并补全项目结构

3.1连接数据库

3.2 使用Easycode生成实体类(比较方便,手写也行)

Easycode会自动生成entity文件夹

3.3 补全项目结构

main下生成resource与Java同级

3.项目架构配置——MyBatis配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!-- 全局设置 -->
    <settings>
        <!-- 自动映射下划线命名字段到驼峰命名属性 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>


    <!-- 默认数据库环境配置 -->
    <environments default="db1">
        <environment id="db1">
            <!-- 使用 JDBC 事务管理器 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 使用内置连接池(推荐替换为 HikariCP 等高性能连接池) -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <!-- 建议根据部署环境调整 serverTimezone -->
                <property name="url" value="jdbc:mysql://localhost:3306/bigbase?serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <!-- 敏感信息建议从外部配置加载,此处为示例 -->
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mappers/StudentMapper.xml"/>
    </mappers>

</configuration>

4.业务代码实现

4.1 实体类

已经自动生成了略过

4.2 mapper接口

与entity同级,创建mapper,放置StudentMapper.java

package com.fei.mapper;

import com.fei.entity.Student;

import java.util.List;

public interface StudentMapper {
    List<Student> selectAllStudents();
}

4.3 配置StudentMapper.xml文件

在resources/mappers下创建StudentMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fei.mapper.StudentMapper">
 <select id="selectAllStudents" resultType="com.fei.entity.Student">
  SELECT sid, name, gender, age FROM student
 </select>

</mapper>

4.4 创建util工具类

与entity同级创建util文件夹,创建JsonUtil.java

package com.fei.util;

import com.alibaba.fastjson.JSON;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class JsonUtil {
    /**
 * 将给定的数据写入到指定的JSON文件中
 * 
 * @param data 要写入文件的数据,可以是任意类型的列表
 * @param filePath 要写入的文件路径
 * @throws IOException 如果在写入文件过程中发生I/O错误
 */
public static void writeToJsonFile(List<?> data, String filePath) throws IOException {
    // 将数据转换为JSON字符串
    String jsonString = JSON.toJSONString(data, true);
    FileWriter writer = null;
    try {
        // 创建FileWriter对象用于写入文件
        writer = new FileWriter(filePath);
        // 将JSON字符串写入文件
        writer.write(jsonString);
    } finally {
        // 确保在所有情况下都关闭FileWriter对象
        if (writer != null) {
            writer.close();
        }
    }
}

}

4.5 创建StudentService

package com.fei.service;

import com.fei.entity.Student;
import com.fei.mapper.StudentMapper;
import com.fei.util.JsonUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class StudentService {
    public static void main(String[] args) {
        // 定义输入流和SqlSession变量
InputStream inputStream = null;
SqlSession session = null;

try {
    // 加载MyBatis配置文件
    inputStream = Resources.getResourceAsStream("mybatis-config.xml");

    // 构建SqlSessionFactory
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);

    // 打开SqlSession
    session = factory.openSession();

    // 获取Mapper实例
    StudentMapper mapper = session.getMapper(StudentMapper.class);

    // 调用Mapper方法查询所有学生
    List<Student> students = mapper.selectAllStudents();

    // 将查询结果转换为JSON格式并写入文件
    JsonUtil.writeToJsonFile(students, "students.json");

    // 打印成功消息
    System.out.println("JSON文件生成成功!");
} catch (IOException e) {
    // 打印异常信息
    e.printStackTrace();
} finally {
    // 关闭SqlSession
    if (session != null) {
        session.close();
    }

    // 关闭输入流
    if (inputStream != null) {
        try {
            inputStream.close();
        } catch (IOException e) {
            // 打印异常信息
            e.printStackTrace();
        }
    }
}

    }
}

5. 运行测试

源数据

测试结果,项目文件夹下students.json

打开看一下

测试一下生成的json文件能否识别


看到这里留下一个小心心吧(づ ̄3 ̄)づ╭

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值