• Java工具库——FastJson的40个常用方法


    在这里插入图片描述那些想看却没看的书,在心里摆满一个图书馆…

    工具库介绍

    阿里巴巴的 FastJSON,也被称为 Alibaba FastJSON 或阿里巴巴 JSON,是一个高性能的 Java JSON 处理库,用于在 Java 应用程序中解析和生成 JSON 数据。FastJSON 以其卓越的性能和功能丰富的特点而闻名,并在阿里巴巴的开源项目和其他许多 Java 应用程序中广泛使用。

    以下是 FastJSON 的主要特点和功能:

    1. 高性能: FastJSON 的性能非常出色,它被设计成一种极快的 JSON 库,可以在读取和写入 JSON 数据时实现卓越的性能。这使得 FastJSON 成为处理大量 JSON 数据的理想选择。

    2. 丰富的功能: FastJSON 提供了丰富的功能,包括将 Java 对象序列化为 JSON 格式和将 JSON 数据解析为 Java 对象。它支持复杂数据类型,包括嵌套对象、集合、数组等。

    3. 简单易用的 API: FastJSON 提供了简单易用的 API,使开发人员能够轻松地进行 JSON 数据的处理。你可以使用 FastJSON 将对象转换为 JSON 字符串,也可以将 JSON 字符串转换为 Java 对象。

    4. 自定义序列化和反序列化: FastJSON 允许你自定义如何将 Java 对象序列化为 JSON 数据以及如何将 JSON 数据反序列化为 Java 对象。这可以用于处理特定的数据格式或数据结构。

    5. 支持标准规范: FastJSON 支持 JSON 规范(RFC 7159),并能够处理 JSON 格式的各种细节,包括转义字符和特殊字符。

    6. 支持日期格式: FastJSON 具有内置的日期序列化和反序列化功能,可以处理日期数据的格式化和解析。

    7. 兼容性: FastJSON 兼容 Java 标准库中的 JSON API,如 javax.json,使得迁移或替换其他 JSON 库变得相对容易。

    8. 广泛应用: FastJSON 在阿里巴巴的许多产品和项目中广泛使用,包括阿里云和淘宝等。

    FastJSON 是一个开源项目,你可以在 GitHub 上找到它的源代码和文档。它的活跃社区和持续的维护使其成为一个受欢迎的 JSON 处理库,适用于各种 Java 应用程序,从小型应用到大型分布式系统。

    方法列举

    FastJSON(阿里巴巴的 JSON 库)提供了大量的方法来处理 JSON 数据。以下是其中一些常用的方法,每个方法都附带了详细解释和示例代码,以及预期的结果。

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import com.alibaba.fastjson.JSONArray;
    
    • 1
    • 2
    • 3

    1. toJSONString():将 Java 对象序列化为 JSON 字符串。

    public static void toJSONStringExample() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "John");
        jsonObject.put("age", 30);
    
        String jsonString = jsonObject.toJSONString();
        System.out.println(jsonString);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2. parseObject():将 JSON 字符串解析为 Java 对象。

    public static void parseObjectExample() {
        String json = "{\"name\":\"Alice\",\"age\":25}";
        JSONObject jsonObject = JSON.parseObject(json);
    
        String name = jsonObject.getString("name");
        int age = jsonObject.getIntValue("age");
    
        System.out.println("Name: " + name + ", Age: " + age);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    3. toJSON():将 Java 对象转换为 JSON 对象。

    public static void toJSONExample() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "Alice");
        jsonObject.put("age", 25);
    
        JSONObject json = (JSONObject) JSON.toJSON(jsonObject);
        System.out.println(json.toJSONString());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    4. parseArray():将 JSON 数组字符串解析为 Java 数组。

    public static void parseArrayExample() {
        String jsonArray = "[1, 2, 3, 4, 5]";
        JSONArray intArray = JSON.parseArray(jsonArray);
    
        int sum = 0;
        for (Object num : intArray) {
            sum += (int) num;
        }
    
        System.out.println("Sum: " + sum);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    5. toJavaObject():将 JSON 对象转换为指定类型的 Java 对象。

    public static class Person {
        public String name;
        public int age;
    }
    
    public static void toJavaObjectExample() {
        String json = "{\"name\":\"Bob\",\"age\":28}";
        Person person = JSON.toJavaObject(JSON.parseObject(json), Person.class);
    
        System.out.println("Name: " + person.name + ", Age: " + person.age);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    6. toJSONBytes():将 Java 对象序列化为 JSON 字节数组。

    public static void toJSONBytesExample() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "Charlie");
        jsonObject.put("age", 35);
    
        byte[] jsonBytes = JSON.toJSONBytes(jsonObject);
        String jsonString = new String(jsonBytes);
        System.out.println(jsonString);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    7. toJSONStringWithDateFormat():使用指定日期格式将 Java 对象序列化为 JSON 字符串。

    public static void toJSONStringWithDateFormatExample() {
        Date today = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "David");
        jsonObject.put("birthDate", sdf.format(today));
    
        String jsonString = JSON.toJSONStringWithDateFormat(jsonObject, "yyyy-MM-dd");
        System.out.println(jsonString);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    8. toJSONStringWithFilter():使用过滤器将 Java 对象序列化为 JSON 字符串。

    public static class Person {
        public String name;
        public int age;
    }
    
    public static void toJSONStringWithFilterExample() {
        Person person = new Person();
        person.name = "Eve";
        person.age = 40;
    
        ValueFilter filter = (object, name, value) -> {
            if (name.equals("age")) {
                return null; // 不包括 "age" 字段
            }
            return value;
        };
    
        String jsonString = JSON.toJSONString(person, filter);
        System.out.println(jsonString);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    9. parse():将 JSON 字符串解析为通用的 java.lang.Object 对象。

    public static void parseExample() {
        String json = "{\"name\":\"Frank\",\"age\":45}";
        Object object = JSON.parse(json);
    
        if (object instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) object;
            String name = jsonObject.getString("name");
            int age = jsonObject.getIntValue("age");
    
            System.out.println("Name: " + name + ", Age: " + age);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    10. isValid():检查 JSON 字符串是否合法。

    public static void isValidExample() {
        String validJson = "{\"name\":\"Grace\",\"age\":50}";
        String invalidJson = "{name\":\"Helen\",\"age\":55}";
    
        boolean valid = JSON.isValid(validJson);
        boolean invalid = JSON.isValid(invalidJson);
    
        System.out.println("Valid JSON: " + valid);
        System.out.println("Invalid JSON: " + invalid);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    11. getJSONObject():获取 JSON 对象中的子对象。

    public static void getJSONObjectExample() {
        String json = "{\"person\":{\"name\":\"Ivy\",\"age\":60}}";
        JSONObject jsonObject = JSON.parseObject(json);
    
        JSONObject personObject = jsonObject.getJSONObject("person");
        String name = personObject.getString("name");
    
        System.out.println("Name: " + name);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    12. getJSONArray():获取 JSON 对象中的子数组。

    public static void getJSONArrayExample() {
        String json = "{\"numbers\":[1, 2, 3, 4, 5]}";
        JSONObject jsonObject = JSON.parseObject(json);
    
        JSONArray numbersArray = jsonObject.getJSONArray("numbers");
        int sum = 0;
    
        for (Object num : numbersArray) {
            sum += (int) num;
        }
    
        System.out.println("Sum: " + sum);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    13. merge():合并两个 JSON 对象。

    public static void mergeExample() {
        String json1 = "{\"name\":\"Jack\"}";
        String json2 = "{\"age\":35}";
    
        JSONObject jsonObject1 = JSON.parseObject(json1);
        JSONObject jsonObject2 = JSON.parseObject(json2);
    
        jsonObject1.putAll(jsonObject2);
        System.out.println(jsonObject1.toJSONString());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    14. size():获取 JSON 对象或数组的元素数量。

    public static void sizeExample() {
        String json = "{\"names\":[\"Mary\",\"Nancy\",\"Oliver\"]}";
        JSONObject jsonObject = JSON.parseObject(json);
    
        JSONArray namesArray = jsonObject.getJSONArray("names");
        int size = namesArray.size();
        System.out.println("Array Size: " + size);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    15. containsKey():检查 JSON 对象是否包含指定的键。

    public static void containsKeyExample() {
        String json = "{\"name\":\"Peter\",\"age\":70}";
        JSONObject
    
     jsonObject = JSON.parseObject(json);
    
        boolean containsAge = jsonObject.containsKey("age");
        boolean containsEmail = jsonObject.containsKey("email");
    
        System.out.println("Contains Age: " + containsAge);
        System.out.println("Contains Email: " + containsEmail);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    16. keySet():获取 JSON 对象的键集合。

    public static void keySetExample() {
        String json = "{\"name\":\"Quincy\",\"age\":75}";
        JSONObject jsonObject = JSON.parseObject(json);
    
        Set<String> keys = jsonObject.keySet();
        for (String key : keys) {
            System.out.println("Key: " + key);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    17. values():获取 JSON 对象的值集合。

    public static void valuesExample() {
        String json = "{\"name\":\"Rachel\",\"age\":80}";
        JSONObject jsonObject = JSON.parseObject(json);
    
        Collection<Object> values = jsonObject.values();
        for (Object value : values) {
            System.out.println("Value: " + value);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    18. remove():从 JSON 对象中删除指定的键。

    public static void removeExample() {
        String json = "{\"name\":\"Sam\",\"age\":85}";
        JSONObject jsonObject = JSON.parseObject(json);
    
        jsonObject.remove("age");
        System.out.println(jsonObject.toJSONString());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    19. clear():清空 JSON 对象中的所有键值对。

    public static void clearExample() {
        String json = "{\"name\":\"Tom\",\"age\":90}";
        JSONObject jsonObject = JSON.parseObject(json);
    
        jsonObject.clear();
        System.out.println(jsonObject.toJSONString());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    20. isEmpty():检查 JSON 对象是否为空。

    public static void isEmptyExample() {
        JSONObject jsonObject = new JSONObject();
    
        boolean empty = jsonObject.isEmpty();
        System.out.println("Is Empty: " + empty);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    21. putAll(Map map): 向 JSON 对象中添加键值对

        public static void putAllExample() {
            JSONObject jsonObject = new JSONObject();
            JSONObject additionalData = new JSONObject();
            additionalData.put("email", "john@example.com");
            additionalData.put("phone", "123-456-7890");
    
            jsonObject.putAll(additionalData);
            System.out.println(jsonObject.toJSONString());
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    22. size(): 获取 JSON 对象的元素数量

        public static void sizeExample() {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "Alice");
            jsonObject.put("age", 30);
    
            int size = jsonObject.size();
            System.out.println("Size: " + size);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    23. containsValue(Object value): 检查 JSON 对象是否包含指定的值

        public static void containsValueExample() {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "Bob");
            jsonObject.put("age", 35);
    
            boolean containsName = jsonObject.containsValue("Bob");
            boolean containsGender = jsonObject.containsValue("Male");
    
            System.out.println("Contains Name: " + containsName);
            System.out.println("Contains Gender: " + containsGender);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    24. keySet(): 获取 JSON 对象的键集合

    public static void keySetExample() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "Charlie");
        jsonObject.put("age", 40);
    
        Set<String> keys = jsonObject.keySet();
        for (String key : keys) {
            System.out.println("Key: " + key);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    25. values(): 获取 JSON 对象的值集合

       public static void valuesExample() {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "David");
            jsonObject.put("age", 45);
    
            Collection<Object> values = jsonObject.values();
            for (Object value : values) {
                System.out.println("Value: " + value);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    26. entrySet(): 获取 JSON 对象的键值对集合

    public static void entrySetExample() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "Eve");
        jsonObject.put("age", 50);
    
        Set<java.util.Map.Entry<String, Object>> entrySet = jsonObject.entrySet();
        for (java.util.Map.Entry<String, Object> entry : entrySet) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    27. putIfAbsent(String key, Object value): 如果不存在键,则向 JSON 对象添加键值对

    public static void putIfAbsentExample() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "Frank");
    
        jsonObject.putIfAbsent("age", 55); // 添加 "age" 键
        jsonObject.putIfAbsent("name", "George"); // 不添加 "name" 键
    
        System.out.println(jsonObject.toJSONString());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    28. put(String key, Object value): 向 JSON 对象添加键值对

       public static void putExample() {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "Helen");
    
            System.out.println(jsonObject.toJSONString());
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    29. get(Object key) : 获取 JSON 对象中的属性值

    public static void getExample() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "Ian");
        jsonObject.put("age", 60);
    
        String name = jsonObject.getString("name");
        int age = jsonObject.getIntValue("age");
    
        System.out.println("Name: " + name + ", Age: " + age);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    30. remove(Object key) : 从 JSON 对象中删除指定的键

    public static void removeExample() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "Jack");
        jsonObject.put("age", 65);
    
        jsonObject.remove("age");
        System.out.println(jsonObject.toJSONString());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    31. putOnce(String key, Object value) : 如果不存在键,则向 JSON 对象添加键值对

      public static void putOnceExample() {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "Kathy");
    
            jsonObject.putOnce("age", 70); // 添加 "age" 键
            jsonObject.putOnce("name", "Laura"); // 不添加 "name" 键
    
            System.out.println(jsonObject.toJSONString());
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    32. putAll(JSONObject m) : 将另一个 JSON 对象中的键值对添加到当前 JSON 对象

    public static void putAllJSONObjectExample() {
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("name", "Mike");
    
        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("age", 75);
        jsonObject2.put("email", "mike@example.com");
    
        jsonObject1.putAll(jsonObject2);
        System.out.println(jsonObject1.toJSONString());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    33. getInteger(String key): 获取 JSON 对象中的整数属性值

    public static void getIntegerExample() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("age", "80"); // 存储为字符串
    
        int age = jsonObject.getInteger("age"); // 解析为整数
        System.out.println("Age: " + age);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    34. getLong(String key) : 获取 JSON 对象中的长整数属性值

      public static void getLongExample() {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("age", "90"); // 存储为字符串
    
            long age = jsonObject.getLong("age"); // 解析为长整数
            System.out.println("Age: " + age);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    35. getShort(String key) : 获取 JSON 对象中的短整数属性值

    public static void getShortExample() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("age", "100"); // 存储为字符串
    
        short age = jsonObject.getShort("age"); // 解析为短整数
        System.out.println("Age: " + age);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    36. getByte(String key) : 获取 JSON 对象中的字节属性值

    public static void getByteExample() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("age", "110"); // 存储为字符串
    
        byte age = jsonObject.getByte("age"); // 解析为字节
        System.out.println("Age: " + age);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    37. getFloat(String key): 获取 JSON 对象中的浮点数属性值

     public static void getFloatExample() {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("height", "175.5"); // 存储为字符串
    
            float height = jsonObject.getFloat("height"); // 解析为浮点数
            System.out.println("Height: " + height);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    38. getDouble(String key) : 获取 JSON 对象中的双精度浮点数属性值

    public static void getDoubleExample() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("weight", "65.5"); // 存储为字符串
    
        double weight = jsonObject.getDouble("weight"); // 解析为双精度浮点数
        System.out.println("Weight: " + weight);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    39. getBoolean(String key): 获取 JSON 对象中的布尔属性值

    public static void getBooleanExample() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("isStudent", "true"); // 存储为字符串
    
        boolean isStudent = jsonObject.getBoolean("isStudent"); // 解析为布尔值
        System.out.println("Is Student: " + isStudent);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    40. getBigDecimal(String key): 获取 JSON 对象中的 BigDecimal 属性值

    public static void getBigDecimalExample() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("price", "99.99"); // 存储为字符串
    
        java.math.BigDecimal price = jsonObject.getBigDecimal("price"); // 解析为 BigDecimal
        System.out.println("Price: " + price);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  • 相关阅读:
    【2023-10-12】如何保证代码质量
    基于STM32+RFID设计的宿舍检修管理系统
    利用idea新创建maven项目时的一些基本配置
    Mac系统 AndroidStudio Missing essential plugin:org.jetbrains.android报错
    主动配电网故障恢复的重构与孤岛划分matlab程序
    【算法三】冒泡排序
    7种链游媒体宣发工具助力游戏营销-华媒舍
    华为机试 - 考古学家
    在vscode中配置anaconda环境的操作感悟
    【JVM】内存模型:原子性、可见性、有序性的问题引出与解决
  • 原文地址:https://blog.csdn.net/weixin_53742691/article/details/134039129