FastJson2

4 阅读4分钟

一,FastJson2介绍

FASTJSON 2是一个性能极致并且简单易用的Java JSON库。

  • FASTJSON 2FASTJSON项目的重要升级,和FASTJSON 1相比,性能有非常大的提升,解决了autoType功能因为兼容和白名单的安全性问题。
  • 性能极致,性能远超过其他流行JSON库,包括jackson/gson/org.json,
  • 支持JDK新特性,包括JDK 11/JDK 17,针对compact string优化,支持Record,支持GraalVM Native-Image
  • 完善的JSONPath支持,支持SQL:2016的JSONPath语法
  • 支持Android 8+,客户端和服务器一套API
  • 支持Kotlin
  • 支持JSON Schema
  • 新增加支持二进制格式JSONB

二,FastJson2基础使用

添加依赖

<dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2</artifactId>
    <version>2.0.52</version>
</dependency>

2.1 Json对象与Json数组的创建

  • Json对象创建

    public void testFastJson(){
        JSONObject info = new JSONObject();
        info.put("name", "张三");
        info.put("age", "18");
        info.put("score", "70");
        System.out.println(info);
    }
    
  • Json数组创建

    @Test
    public void testFastJson(){
        JSONObject obj = new JSONObject();
        JSONArray array = new JSONArray();
        array.add("1班");
        array.add("2班");
        array.add("3班");
        obj.put("class",array);
        System.out.println(obj);
    }
    

2.2 Json对象的取值与Json数组遍历取值

  • Json对象取值

    通过get方法可以获取值,但是返回的是Object对象,如果想返回指定对象可以通过getXXX来实现

    @Test
    public void testFastJson(){
        JSONObject rootNode = new JSONObject();
        rootNode.put("name", "名字");
        rootNode.put("age",13);
        rootNode.put("date", "2022-01-01");
        rootNode.put("isOpen",true);
        JSONArray array = new JSONArray();
        array.add(1);
        array.add(2);
        rootNode.put("array",array);
        JSONObject son=new JSONObject();
        son.put("name","张三");
        son.put("age",13);
        rootNode.put("son",son);
    
        
        //取值
        Object name = rootNode.get("name");
        String string = rootNode.getString("name");
        Integer age = rootNode.getInteger("age");
        Boolean isOpen = rootNode.getBoolean("isOpen");
        JSONArray jSONArray = rootNode.getJSONArray("array");
        JSONObject sonNode = rootNode.getJSONObject("son");
    
    }
    
  • Json数组遍历取值

    @Test
    public void testFastJson(){
        JSONObject info1 = new JSONObject();
        info1.put("name", "张三");
        info1.put("age", "18");
        JSONObject info2 = new JSONObject();
        info2.put("name", "李四");
        info2.put("age", "19");
    
        JSONArray array = new JSONArray();
        array.add(info1);
        array.add(info2);
        //遍历获取json数组中对象的值
        for (int i = 0; i < array.size(); i++) {
            JSONObject json = array.getJSONObject(i);
            System.out.println(json.getString("name"));
            System.out.println(json.getString("age"));
        }
    

2.3 Json对象与Json数组的其他操作

  • Json对象的删除key,更新key,新增key

    @Test
    public void testFastJson(){
        JSONObject obj = new JSONObject();
        //新增(可以新增JSON对象,JSON数组,Object数据类型)
        obj.put("name","张三");
        obj.put("age","13");
        //删除
        obj.remove("age");
        //修改(多次对同一个key进行put就是修改)
        obj.put("name","李四");
    
        System.out.println(obj);
    }
    
  • Json数组的新增,删除,修改

    @Test
    public void testFastJson(){
        JSONArray array = new JSONArray();
        //新增(可以新增Object类型的)
        array.add("a");
        array.add("b");
        //指定index新增,从0开始
        array.add(1,123);
        //删除(根据index删除)
        array.remove(1);
        //修改,根据index修改
        array.set(1, "c");
        System.out.println(array);
    }
    

2.4 Json对象/数组与字符串转化

  • json对象与字符串的转换

    @Test
    public void testFastJson(){
        JSONObject info = new JSONObject();
        info.put("name", "张三");
        info.put("age", "18");
        info.put("地理", "70");
        info.put("英语", "60");
    
        //JSON对象转字符串
        String str = JSON.toJSONString(info);
        //字符串转JSON对象
        JSONObject json = JSONObject.parseObject(str);
    
    }
    
  • 字符串的字节数组转json对象

    @Test
    public void testFastJson(){
            String str = "{\"name\":\"张三\",\"age\":\"18\",\"地理\":\"70\",\"英语\":\"60\"}";
    
            byte[] bytes = str.getBytes();
            JSONObject data = JSON.parseObject(bytes);
    }
    
  • Json数组与字符串的转化

    @Test
    public void testFastJson(){
            String text = "[\"张三\",\"李四\",\"王五\"]";
            //字符串转json数组
            JSONArray data = JSON.parseArray(text);
            //json数组转字符串
            String str = JSONArray.toJSONString(data);
    }
    

2.5 字符串与javabean转化

  1. User类如下

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @ToString
    public class User {
        public String name;
        public int age;
    }
    
  2. 字符串与javaBean转化

    @Test
    public void testFastJson(){
        User user = new User("张三",20);
        //将javabean转化为字符串
        String str = JSON.toJSONString(user);
        //将字符串转化为javabean
        User user1 = JSON.parseObject(str, User.class);
    }
    
  3. javabean与字节数组转换

    @Test
    public void testFastJson(){
        User user = new User("张三",20);
        //将javabean转化为字符串
        byte[] bytes = JSON.toJSONBytes(user);
        //将字符串转化为javabean
        User user1 = JSON.parseObject(bytes, User.class);
    }
    

2.6 字符串与Map转换

  • 字符串转Map

    @Test
    public void testFastJson(){
        String str="{\n" +
                "\"gradle\":\"高一\",\n" +
                "\"number\":\"2\",\n" +
                "\"people\":[{\"name\":\"张三\",\"age\":\"15\",\"phone\":\"123456\"},\n" +
                "         {\"name\":\"李四\",\"age\":\"16\",\"phone\":\"78945\"}]\n" +
                "}";
    
        //json字符串转Map
        Map<String, Object> map = JSONObject.parseObject(str, new TypeReference<Map<String, Object>>() {});
        System.out.println(map.get("gradle").toString());
        System.out.println(map.get("number").toString());
        System.out.println(map.get("people").toString());
        
    }
    
  • map转字符串

    @Test
    public void testFastJson(){
        Map<String,String> map=new HashMap<>();
        map.put("测试1",null);
        map.put("测试2","hello");
    
        //{"测试2":"hello","测试1":null}
        String str = JSON.toJSONString(map, JSONWriter.Feature.WriteMapNullValue);
        System.out.println(str);
    
    }
    

2.7 字符串与List转换

@Test
public void testFastJson(){
    String str="{\n" +
            "\"gradle\":\"高一\",\n" +
            "\"number\":\"2\",\n" +
            "\"people\":[{\"name\":\"张三\",\"age\":\"15\",\"phone\":\"123456\"},\n" +
            "         {\"name\":\"李四\",\"age\":\"16\",\"phone\":\"78945\"}]\n" +
            "}";

    JSONObject strJson = JSONObject.parseObject(str);
    //获取people数组
    JSONArray people = strJson.getJSONArray("people");
    //json数组转List
    List<Map> list = people.toJavaList(Map.class);
}

如果直接使用JSON.toJSONString(map)转换,因为"测试1"的值为null,转换的结果就会是 {“测试2”:“hello”}

2.8 格式化输出

@Test
public void testFastJson(){
    String str = "[{\"isSendPhone\":\"true\",\"id\":\"22258352\",\"phoneMessgge\":\"为避免影响您的正常使用请及时续费,若已续费请忽略此信息。\",\"readsendtime\":\"9\",\"countdown\":\"7\",\"count\":\"5\",\"serviceName\":\"流程助手\",\"startdate\":\"2022-02-09 00:00:00.0\",\"insertTime\":\"2023-02-02 07:00:38.0\",\"enddate\":\"2023-02-08 23:59:59.0\",\"emailMessage\":\"为避免影响您的正常使用请及时续费,若已续费请忽略此信息。\",\"phone\":\"\",\"companyname\":\"顾问有限责任公司\",\"serviceId\":\"21\",\"isSendeMail\":\"true\",\"email\":\"\"},{\"isSendPhone\":\"true\",\"eid\":\"7682130\",\"phoneMessgge\":\"为避免影响您的正常使用请及时续费,若已续费请忽略此信息。\",\"readsendtime\":\"9\",\"countdown\":\"15\",\"count\":\"50\",\"serviceName\":\"经理人自助服务\",\"startdate\":\"2022-02-17 00:00:00.0\",\"insertTime\":\"2023-02-02 07:00:38.0\",\"enddate\":\"2023-02-16 23:59:59.0\",\"emailMessage\":\"为避免影响您的正常使用请及时续费,若已续费请忽略此信息。\",\"phone\":\"\",\"companyname\":\"生物科技股份有限公司\",\"serviceId\":\"2\",\"isSendeMail\":\"true\",\"email\":\"\"}]";

    str =  str.trim();
    String formatStr = null;
    if (str.startsWith("[")) {
        JSONArray data = JSON.parseArray(str);
        formatStr = JSONArray.toJSONString(data, JSONWriter.Feature.PrettyFormat, JSONWriter.Feature.WriteMapNullValue, JSONWriter.Feature.WriteNullListAsEmpty);
    } else {
        JSONObject strJson = JSONObject.parseObject(str);
        formatStr = JSON.toJSONString(strJson, JSONWriter.Feature.PrettyFormat, JSONWriter.Feature.WriteMapNullValue, JSONWriter.Feature.WriteNullListAsEmpty);
    }
    
    System.out.println(formatStr);
    
}

三,SpringBoot集成fastjson2

详见官方文档:fastjson2/docs/spring_support_cn.md at main · alibaba/fastjson2 (github.com)