iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > JAVA >fastjson2 介绍及使用
  • 647
分享到

fastjson2 介绍及使用

javafastjson2fastjsonfastJson 2023-08-18 19:08:39 647人浏览 八月长安
摘要

目录 前言一、导入fastjson2依赖二、json对象与json数组的创建json对象创建json数组创建 三、json对象取值与json数组遍历取值json对象取值json数组遍历取值 四、json对象与字符串的转换js

前言

fastJSON2 是 FASTjsON 项目的重要升级,目标是为下一个十年提供一个高性能的JSON库, fastjson2 性能相比原先旧的 fastjson 有了很大提升,并且 fastjson2 更安全,完全删除autoType白名单,提升了安全性。

关于fastjson2升级指南
fastjson2 的github地址

一、导入fastjson2依赖

Maven如下:

        <dependency>            <groupId>com.alibaba.fastjson2groupId>            <artifactId>fastjson2artifactId>            <version>2.0.26version>        dependency>

需要注意的一点是在使用 fastjson2 时导入的包名是 com.alibaba.fastjson2 ,就像下面这样:

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

二、json对象与json数组的创建

json对象创建

        JSONObject info = new JSONObject();        info.put("name", "张三");        info.put("age", "18");        info.put("地理", "70");        info.put("英语", "60");

json数组创建

JSONObject info1 = new JSONObject();        info1.put("name", "张三");        info1.put("age", "18");        JSONObject info2 = new JSONObject();        info2.put("name", "李四");        info2.put("age", "19");        //把上面创建的两个json对象加入到json数组里        JSONArray array = new JSONArray();        array.add(info1);        array.add(info2);
        JSONArray array = new JSONArray();        array.add("1班");        array.add("2班");        array.add("3班");

三、json对象取值与json数组遍历取值

json对象取值

        JSONArray array = new JSONArray();        array.add("1班");        array.add("2班");        array.add("3班");        JSONObject school = new JSONObject();        school.put("schoolName", "第一中学");        school.put("teacher", "刘梅");        JSONObject info = new JSONObject();        info.put("name", "张三");        info.put("age", "18");        info.put("gradle",array);        info.put("schoolInfo",school);        //从info中取值        System.out.println(info.getString("name")); //张三        System.out.println(info.getIntValue("age"));//18        System.out.println(info.getJSONArray("gradle"));//["1班","2班","3班"]        System.out.println(info.getJSONObject("schoolInfo"));//{"schoolName":"第一中学","teacher":"刘梅"}

json数组遍历取值

        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"));        }

四、json对象与字符串的转换

json对象与字符串的转换

JSONObject info = new JSONObject();        info.put("name", "张三");        info.put("age", "18");        info.put("地理", "70");        info.put("英语", "60");        //JSON对象转字符串        String str = JSON.toJSONString(info);        //JSON字符串转JSON对象        JSONObject json = JSONObject.parseObject(str);

json字符串的字节数组转json对象

        String str = "{\"name\":\"张三\",\"age\":\"18\",\"地理\":\"70\",\"英语\":\"60\"}";        byte[] bytes = str.getBytes();        JSONObject data = JSON.parseObject(bytes);

五、json数组与字符串的转换

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

六、json字符串转java对象的转换

Student类如下:

public class Student {    public String name;    public int age;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public Student(String name, int age) {        this.name = name;        this.age = age;    }}

json字符串转java对象的转换

        Student student = new Student("张三", 18);        //Student对象转JSON字符串        String studentStr = JSON.toJSONString(student);        //JSON字符串转Student对象        Student data = JSON.parseObject(studentStr, Student.class);

java对象转byte数组转换

        Student student = new Student("张三", 18);        //Student对象转字节数组        byte[] text = JSON.toJSONBytes(student);        //字节数组转Student对象        Student data = JSON.parseObject(text, Student.class);

七、json字符串与Map转换

json字符串转Map

        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转json字符串

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

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);

如果你使用的是老的fastjson1,可以像下面这样转换:

Map<String,String> map=new HashMap<>();map.put("测试1",null);map.put("测试2","hello");String str = JSON.toJSONString(map, SerializerFeature.WriteMapNullValue) ;

八、json数组转List

        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);

如果你使用的是老的fastjson1,可以像下面这样转换:

        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);//字符串转json对象        String people = String.valueOf(strJson.getJSONArray("people"));        List<Map<String,String>> list = (List<Map<String,String>>) JSONArray.parse(people);

九、json字符串格式化

有时候我们想把 json 字符串格式化输出,也就是该缩进的缩进该换行的换行,让它更美观的输出,可以像下面这样:

        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);

输出结果:

[{"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":"XX顾问有限责任公司","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":"XX科技股份有限公司","serviceId":"2","isSendeMail":"true","email":""}]

参考:
fastjson2

来源地址:https://blog.csdn.net/qq_33697094/article/details/128114939

--结束END--

本文标题: fastjson2 介绍及使用

本文链接: https://www.lsjlt.com/news/374577.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • fastjson2 介绍及使用
    目录 前言一、导入fastjson2依赖二、json对象与json数组的创建json对象创建json数组创建 三、json对象取值与json数组遍历取值json对象取值json数组遍历取值 四、json对象与字符串的转换js...
    99+
    2023-08-18
    java fastjson2 fastjson fastJson
  • Apache介绍及使用
    Apache的介绍 Apache全称:Apache HTTPD Server ;是Apache基金会的一个开源网页服务器,可以在大多数计算机操作系统中运行。Apache提供的服务器又称为:补丁服务器 ...
    99+
    2023-09-17
    apache php 服务器
  • Numpy库的介绍及使用
    Numpy库的介绍及使用 1. Numpy库入门1.1 数据的维度1.2 ndarray的优势1.3 ndarray对象的属性1.4 ndarray数组的创建和变换1.4.1 ndarray数...
    99+
    2023-09-04
    numpy python
  • Jupyter 介绍、安装及使用
    Jupyter 介绍、安装及使用 一.Jupyter介绍 Jupyter Notebook是一个开源的web应用程序,可以使用它来创建和共享包含实时代码、方程、可视化和文本的文档。 Jupyter ...
    99+
    2023-09-05
    python
  • Delphi中QuotedStr介绍及使用
    在Delphi中,QuotedStr是一个函数,用于将字符串用引号括起来。QuotedStr函数接受一个字符串参数,并返回引号括起来...
    99+
    2023-09-20
    Delphi
  • Matplotlib库的介绍及使用
    Matplotlib库的介绍及使用 1. pyplot子库的基本使用1.1 Matplotlib库的介绍1.2 plot函数1.3 pyplot的中文显示1.4 pyplot的文本显示 2...
    99+
    2023-10-02
    matplotlib python numpy
  • plt.subplot()参数及使用介绍
    plt.subplot() plt.subplot(nrows, ncols, index, **kwargs) 第一个参数:*args (官网文档描述)Either a 3-dig...
    99+
    2023-01-11
    plt.subplot()使用
  • .NetCoreSDK命令介绍及使用
    dotnet run 介绍 dotnet 相关命令是属于 .NET Core command-line (CLI) 的一部分,Microsoft 为我们提供了这个命令行工具以供我们在...
    99+
    2024-04-02
  • ReentrantLock介绍及使用(超详细)
    点击 Mr.绵羊的知识星球 解锁更多优质文章。 目录 一、介绍 1. 简介 2. 是什么类型的锁 3. 优点 4. 原理 5. 主要方法 6. 使用时注意事项 二、实际应用 1. 案例一 2. 案例二 一、介绍 1. 简介     ...
    99+
    2023-09-20
    java 开发语言
  • Json优缺点及使用介绍
    目录1. 什么是 JSON1.1 数组字面量1.2 对象字面量1.3 混合字面量1.4 JSON 语法1.5 JSON 编码和解码2. JSON 与 XML3. 服务器端 JSON ...
    99+
    2024-04-02
  • 【Tomcat】Tomcat 介绍及使用教程
    文章目录 1. Tomcat 介绍2. 下载安装2.1 Windows 中安装2.2 Linux 中安装2.3 访问 Tomcat 3. Tomcat 的目录结构4. Tomcat 的配置...
    99+
    2023-10-03
    tomcat java-ee java
  • java中BigDecimal的介绍及使用
    BigDecimal是Java中的一个类,用于表示任意精度的十进制数。它提供了精确的数值计算,避免了浮点数计算时的精度损失。使用Bi...
    99+
    2023-09-09
    java
  • futuretask用法及使用场景介绍
    FutureTask可用于异步获取执行结果或取消执行任务的场景。通过传入Runnable或者Callable的任务给FutureTask,直接调用其run方法或者放入线程池执行,之后可以在外部通过FutureTask的get方法异步获取执行...
    99+
    2023-05-31
    java futuretask
  • java基础之NIO介绍及使用
    目录一、NIO二、三大组件三、ByteBuffer的使用四、测试Demo五、Channel的使用六、网络编程七、Selector八、网络编程(多路复用)一、NIO java.nio...
    99+
    2024-04-02
  • Python 之plt.plot()的介绍以及使用
    文章目录 介绍代码实例 介绍 plt.plot() 是Matplotlib库中用于绘制线图(折线图)的主要函数之一。它的作用是将一组数据点连接起来,以可视化数据的趋势、关系或模式。以下是...
    99+
    2023-10-23
    python 开发语言
  • Tushare介绍、安装及使用教程
            本人是一个二本大数据的学生,想未来从事数据分析师的岗位。虽然说路漫漫道阻且长,但是我还是想跟大家分享一下平时做一些数据分析喜欢用的数据源,如果大家看完我的文章后,有什么不好的地方欢迎大家在评论区写下宝贵的意见,我看到都会积极...
    99+
    2023-10-08
    python
  • JavaScriptwebpack5配置及使用基本介绍
    目录一、webpack1.1 简介1.2 五大核心概念entry (入口)output (出口)loaderplugin (插件)mode (模式)二、配置及使用项目结构使用html...
    99+
    2024-04-02
  • libmp3lame及API介绍和使用详解
    目录API介绍简单使用API介绍 API地址是对libmp3lame.so的编码部分最基础接口的介绍,本库特包含了增加id3标签和mp3的解码的支持。这里并不是完整的文档,但是你可以...
    99+
    2023-05-18
    libmp3lame API使用 libmp3lame API
  • Kotlinby关键字作用及使用介绍
    目录1.Kotlin委托2.类委托3.属性委托3.1定义一个被委托的类3.2标准委托3.3把属性存储在映射中3.4Not Null1.Kotlin委托 在委托模式中,两个对象参与处理...
    99+
    2024-04-02
  • TIDB简介及TIDB部署、原理和使用介绍
    TiDB简介及TiDB部署、原理和使用介绍 从MySQL架构到TiDB 数据库分类 ​ 介绍TiDB数据库之前,先引入使用场景。如今的数据库种类繁多,RDBMS(关系型数据库)、NoSQL(Not Only SQL)、NewSQL,在数据库...
    99+
    2023-08-17
    tidb 数据库 mysql 大数据 etl工程师
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作