FastJSON2 常用工具类详解与实战指南

好的,以下是一份系统性、综合性、全面的 FastJSON2 常用工具类详细说明文档,包含表格、详细使用示例和实际开发建议。


✅ FastJSON2 常用工具类详解与实战指南

📌 一、FastJSON2 常用工具类总览表

工具类作用核心方法常见用法场景
JSON核心序列化/反序列化入口toJSONString(), parseObject(), parseArray()所有 JSON 转换、API 响应、配置解析
JSONObject动态 JSON 对象(类似 Map)get(), put(), getString(), getInteger()配置动态读取、日志结构化、API 响应构建
JSONArray动态 JSON 数组(类似 List)add(), get(), getJSONObject(), size()批量数据处理、列表响应构建
JSONB二进制 JSON 序列化/反序列化toBytes(), parseObject(byte[])高性能缓存、RPC、消息队列
JSONPathJSON 数据路径查询read()从复杂 JSON 中提取部分数据
TypeReference泛型类型引用<init>()解析泛型集合 List<T>, Map<K,V>
SerializerFeature序列化选项枚举值控制输出格式(是否输出 null、是否格式化)
JSONReader.Feature反序列化选项枚举值控制解析行为(忽略大小写、允许注释)

📌 二、各工具类详细使用示例(含中文注释)

✅ 1. JSON 工具类

import com.alibaba.fastjson2.JSON;
import java.util.List;

// 定义一个简单的 JavaBean
class User {
    private Long id;
    private String name;
    private String email;

    public User() {} // 必须有无参构造器

    // Getter/Setter (此处省略,实际项目推荐用 Lombok @Data)
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
}

public class JsonExample {
    public static void main(String[] args) {
        // --- 1.1 序列化 Java 对象为 JSON 字符串 ---
        User user = new User();
        user.setId(1L);
        user.setName("张三");
        user.setEmail("zhangsan@company.com");

        // 将 Java 对象序列化为 JSON 字符串
        String jsonString = JSON.toJSONString(user);
        System.out.println("序列化结果: " + jsonString);
        // 输出: {"email":"zhangsan@company.com","id":1,"name":"张三"}

        // --- 1.2 反序列化 JSON 字符串为 Java 对象 ---
        String jsonInput = "{\"id\":2,\"name\":\"李四\",\"email\":\"lisi@company.com\"}";
        User parsedUser = JSON.parseObject(jsonInput, User.class); // 指定目标类,安全
        System.out.println("反序列化结果: " + parsedUser.getName()); // 输出: 李四

        // --- 1.3 反序列化 JSON 字符串为 Java 对象集合 (使用 TypeReference) ---
        String jsonArrayStr = "[{\"id\":3,\"name\":\"王五\",\"email\":\"wangwu@company.com\"},{\"id\":4,\"name\":\"赵六\",\"email\":\"zhaoliu@company.com\"}]";
        List<User> userList = JSON.parseArray(jsonArrayStr, User.class);
        // List<User> userList = JSON.parseObject(jsonArrayStr, new TypeReference<>() {});
        System.out.println("反序列化集合大小: " + userList.size()); // 输出: 2
        System.out.println("第一个用户: " + userList.get(0).getName()); // 输出: 王五
    }
}

✅ 2. JSONObject 工具类

import com.alibaba.fastjson2.JSONObject;
import java.util.Map;

public class JsonObjectExample {
    public static void main(String[] args) {
        // --- 2.1 从 JSON 字符串解析为 JSONObject ---
        String jsonStr = "{\"code\":200,\"message\":\"success\",\"data\":{\"userId\":1001,\"userName\":\"admin\"}}";
        JSONObject response = JSONObject.parseObject(jsonStr);

        // 获取基本类型值
        int code = response.getIntValue("code"); // getIntValue 自动转换为 int
        String message = response.getString("message");
        System.out.println("状态码: " + code + ", 消息: " + message);

        // 获取嵌套的 JSONObject
        JSONObject data = response.getJSONObject("data");
        Long userId = data.getLong("userId");
        String userName = data.getString("userName");
        System.out.println("用户ID: " + userId + ", 用户名: " + userName);

        // --- 2.2 动态构建 JSONObject ---
        JSONObject config = new JSONObject();
        config.put("appName", "InsuranceApp");
        config.put("version", "2.1.0");
        config.put("debug", true);

        // 添加一个 Map 作为值,它会自动转换为 JSONObject
        Map<String, Object> database = Map.of("host", "localhost", "port", 5432);
        config.put("database", database);

        System.out.println("构建的配置 JSON: " + config.toJSONString());

        // --- 2.3 安全获取值(避免 NPE) ---
        String nonExistentValue = response.getString("nonexistent", "default_value");
        System.out.println("不存在的键的默认值: " + nonExistentValue); // 输出: default_value
    }
}

✅ 3. JSONArray 工具类

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

public class JsonArrayExample {
    public static void main(String[] args) {
        // --- 3.1 从 JSON 字符串解析为 JSONArray ---
        String jsonArrayStr = "[{\"name\":\"苹果\",\"price\":5.5},{\"name\":\"香蕉\",\"price\":3.2},{\"name\":\"橙子\",\"price\":4.8}]";
        JSONArray fruits = JSONArray.parseArray(jsonArrayStr);

        // 遍历数组
        for (int i = 0; i < fruits.size(); i++) {
            JSONObject fruit = fruits.getJSONObject(i); // 获取数组中每个元素为 JSONObject
            String name = fruit.getString("name");
            Double price = fruit.getDouble("price");
            System.out.println("水果: " + name + ", 价格: " + price);
        }

        // --- 3.2 动态构建 JSONArray ---
        JSONArray permissions = new JSONArray();
        permissions.add("read"); // 添加字符串
        permissions.add("write");
        permissions.add(true); // 添加布尔值
        permissions.add(123); // 添加数字

        System.out.println("权限列表: " + permissions.toJSONString());

        // --- 3.3 从 JSONObject 中获取 JSONArray ---
        String complexJson = "{\"user\":{\"name\":\"张三\",\"hobbies\":[\"读书\",\"游泳\",\"编程\"]}}";
        JSONObject complexObj = JSONObject.parseObject(complexJson);
        JSONArray hobbies = complexObj.getJSONObject("user").getJSONArray("hobbies");
        System.out.println("爱好列表: " + hobbies);
    }
}

✅ 4. JSONB 工具类

import com.alibaba.fastjson2.JSONB;

public class JsonbExample {
    public static void main(String[] args) {
        User user = new User();
        user.setId(100L);
        user.setName("JSONB 用户");
        user.setEmail("jsonb@fastjson.com");

        // --- 4.1 序列化为 JSONB 字节数组 ---
        byte[] jsonbBytes = JSONB.toBytes(user);
        System.out.println("JSONB 字节数组长度: " + jsonbBytes.length); // 比 JSON 字符串小很多
        System.out.println("JSONB 字节数组 (Hex): " + bytesToHex(jsonbBytes));

        // --- 4.2 从 JSONB 字节数组反序列化为 Java 对象 ---
        User deserializedUser = JSONB.parseObject(jsonbBytes, User.class);
        System.out.println("从 JSONB 反序列化结果: " + deserializedUser.getName());
        // 输出: 从 JSONB 反序列化结果: JSONB 用户
    }

    // 辅助方法:将字节数组转为十六进制字符串,便于查看
    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }
}

✅ 5. JSONPath 工具类

import com.alibaba.fastjson2.JSONPath;

public class JsonPathExample {
    public static void main(String[] args) {
        String complexJson = """
            {
              "store": {
                "book": [
                  {
                    "category": "reference",
                    "author": "Nigel Rees",
                    "title": "Sayings of the Century",
                    "price": 8.95
                  },
                  {
                    "category": "fiction",
                    "author": "Evelyn Waugh",
                    "title": "Sword of Honour",
                    "price": 12.99
                  }
                ],
                "bicycle": {
                  "color": "red",
                  "price": 19.95
                }
              },
              "expensive": 10
            }
            """;

        // --- 5.1 从 JSON 字符串中读取数据 ---
        // 获取所有书籍的标题
        Object titles = JSONPath.read(complexJson, "$.store.book[*].title");
        System.out.println("所有书籍标题: " + titles); // 输出: [Sayings of the Century, Sword of Honour]

        // 获取第一本书的价格
        Object firstBookPrice = JSONPath.read(complexJson, "$.store.book[0].price");
        System.out.println("第一本书价格: " + firstBookPrice); // 输出: 8.95

        // 获取自行车的颜色
        Object bikeColor = JSONPath.read(complexJson, "$.store.bicycle.color");
        System.out.println("自行车颜色: " + bikeColor); // 输出: red

        // --- 5.2 从 JSONB 字节数组中读取数据 ---
        byte[] jsonbBytes = JSONB.toBytes(complexJson); // 将 JSON 字符串转为 JSONB 字节数组
        Object expensiveValue = JSONPath.read(jsonbBytes, "$.expensive"); // 直接从字节数组读取,性能更高
        System.out.println("expensive 值: " + expensiveValue); // 输出: 10
    }
}

✅ 6. TypeReference 工具类

import com.alibaba.fastjson2.JSON;
import java.util.List;
import java.util.Map;

public class TypeReferenceExample {
    public static void main(String[] args) {
        // --- 6.1 解析泛型 List ---
        String listJson = "[{\"name\":\"产品A\",\"price\":100},{\"name\":\"产品B\",\"price\":200}]";
        List<Product> productList = JSON.parseObject(listJson, new com.alibaba.fastjson2.TypeReference<List<Product>>() {});
        System.out.println("产品列表大小: " + productList.size());

        // --- 6.2 解析泛型 Map ---
        String mapJson = "{\"key1\":{\"name\":\"商品1\"},\"key2\":{\"name\":\"商品2\"}}";
        Map<String, Product> productMap = JSON.parseObject(mapJson, new com.alibaba.fastjson2.TypeReference<Map<String, Product>>() {});
        System.out.println("Map 中 key1 对应的商品名: " + productMap.get("key1").getName());

        // --- 6.3 解析复杂嵌套泛型 ---
        String nestedJson = "[{\"groupId\":\"G1\",\"items\":[{\"name\":\"Item1\"},{\"name\":\"Item2\"}]}]";
        List<Group> groups = JSON.parseObject(nestedJson, new com.alibaba.fastjson2.TypeReference<List<Group>>() {});
        System.out.println("分组数量: " + groups.size());
    }

    // 辅助类
    static class Product {
        private String name;
        private Double price;
        // getter/setter (省略)
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public Double getPrice() { return price; }
        public void setPrice(Double price) { this.price = price; }
    }

    static class Group {
        private String groupId;
        private List<Product> items;
        // getter/setter (省略)
        public String getGroupId() { return groupId; }
        public void setGroupId(String groupId) { this.groupId = groupId; }
        public List<Product> getItems() { return items; }
        public void setItems(List<Product> items) { this.items = items; }
    }
}

✅ 7. SerializerFeature 工具类

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.config.JSONWriter;

public class SerializerFeatureExample {
    public static void main(String[] args) {
        User user = new User();
        user.setId(1L);
        user.setName("张三");
        // user.setEmail(null); // 假设 email 为 null

        // --- 7.1 默认序列化(忽略 null 字段) ---
        String defaultJson = JSON.toJSONString(user);
        System.out.println("默认序列化: " + defaultJson); // 输出: {"id":1,"name":"张三"}

        // --- 7.2 序列化时输出 null 字段 ---
        String withNullJson = JSON.toJSONString(user, JSONWriter.Feature.WriteMapNullValue);
        System.out.println("输出 null 字段: " + withNullJson); // 输出: {"email":null,"id":1,"name":"张三"}

        // --- 7.3 格式化输出(美化) ---
        String prettyJson = JSON.toJSONString(user, JSONWriter.Feature.PrettyFormat);
        System.out.println("格式化输出:\n" + prettyJson);
        /*
        输出:
        {
            "id": 1,
            "name": "张三"
        }
        */

        // --- 7.4 组合多个 Feature ---
        String combinedJson = JSON.toJSONString(user,
                JSONWriter.Feature.WriteMapNullValue, // 输出 null
                JSONWriter.Feature.PrettyFormat      // 格式化
        );
        System.out.println("组合 Feature 输出:\n" + combinedJson);
    }
}

✅ 8. JSONReader.Feature 工具类

import com.alibaba.fastjson2.JSON;

public class JsonReaderFeatureExample {
    public static void main(String[] args) {
        // JSON 字段名与 JavaBean 不完全匹配(大小写不一致)
        String jsonWithWrongCase = "{\"Name\":\"李四\",\"AGE\":30,\"Email\":\"lisi@company.com\"}";

        // --- 8.1 默认反序列化(严格匹配,会失败) ---
        try {
            User user = JSON.parseObject(jsonWithWrongCase, User.class);
            System.out.println("默认反序列化结果: " + user.getName()); // 可能为 null
        } catch (Exception e) {
            System.out.println("默认反序列化失败或字段映射失败");
        }

        // --- 8.2 使用 Feature 忽略字段名大小写 ---
        User userIgnoreCase = JSON.parseObject(jsonWithWrongCase, User.class,
                com.alibaba.fastjson2.config.JSONReader.Feature.IgnoreCase);
        System.out.println("忽略大小写反序列化结果: " + userIgnoreCase.getName()); // 输出: 李四
        System.out.println("年龄: " + userIgnoreCase.getAge()); // 输出: 30
    }
}

📌 三、实际开发使用建议

类别建议说明
核心使用优先使用 JSON.toJSONString()JSON.parseObject(json, Class.class)简洁、安全、性能好
泛型处理使用 TypeReference 解析 List<T>, Map<K,V>避免泛型擦除导致类型错误
性能优化高并发、低延迟场景(如缓存、RPC)使用 JSONB比 JSON 字符串序列化快 3~5 倍,体积小 40%
数据提取从复杂 JSON 中只取部分字段 → 使用 JSONPath.read()避免反序列化整个对象,节省 CPU 和内存
安全防护严禁使用 JSON.parse(String) 解析不可信输入该方法可能引发反序列化漏洞,始终使用 parseObject(json, TargetClass.class)
空值处理在 Spring Boot 配置中全局设置 WriteMapNullValue 等 Feature统一处理 null 值,避免前端报错
日期格式使用 @JSONField(format="yyyy-MM-dd HH:mm:ss") 注解避免默认时间戳格式,提升可读性
Spring Boot 集成显式配置 FastJSON2 作为默认 JSON 序列化器避免 Jackson 与 FastJSON2 冲突,确保性能
日志打印调试时使用 toJSONString(obj, PrettyFormat)便于阅读,但生产环境应关闭,避免性能损耗
版本管理始终使用最新稳定版修复了历史安全漏洞,性能持续优化
团队规范在团队代码规范中强制要求使用 parseObject(json, Class.class)从源头杜绝安全风险

✅ 总结

FastJSON2 提供了功能强大且灵活的工具类,涵盖了从基本的序列化/反序列化到高性能的二进制格式和路径查询。在实际开发中,应根据具体场景选择合适的工具和方法,特别是在性能敏感和安全要求高的项目(如银行、保险系统)中,合理运用 JSONBJSONPath 能显著提升系统效率和安全性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙茶清欢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值