FastJson中JSONString与各个对象的的转换关系及API示例
前言
JSON作为一种轻量级的数据交换格式,在我们日常的开发中使用十分广泛,就Java后端的开发工作中,JSON字符串与Java对象之间相互转换是常常遇到的操作。
虽然平时用到的挺多的,但是因为用于JSON处理的包有很多种,每种工具集的功能和使用方式也都不同,很容易在使用时造成混乱。
本文就结合
FastJson部分源码,简单整理了下常用的API及其使用示例
本文FastJson版本:1.2.54
转换图
根据FastJson源码大致整理出了这么一张转换图:

可以看到参与转换的对象主要有图中五种:
- JSONString:
json字符串 - JSONObject:
json对象 - JSONArray:
json对象数组 - JavaBean:
java对象 - List:
java对象集合
转化中用到的方法的方法名有如下几种:
- parse:
JSONString ==> JSONObject/JSONArray - parseObject:
JSONString ==> JSONObject/JavaBean - pareseArray:
JSONString ==> JSONObject/List<JavaBean> - toJSONString:
JavaBean/JSONObject ==> JSONString - toJSON:
JavaBean ==> JSONObject - toJavaObject:
JSONObject ==> JavaBean
常用API
本文种仅列举
平常使用频率较高的API,其他的重载方法可参考源码,大都是对序列化/反序列化过程进行定制化。
toJSONString
实现了json对象(
JSONObject)>json字符串(JSONString),和Java对象(JavaBean)>json字符串(JSONString)的转化

从源码中可以看到这一方法被重载了多个,我们日常会用到的有如下几个:
| 方法 : 返回值 | 参数说明 | 功能 |
|---|---|---|
| toJSONString(Object object):String | object: 需要进行序列化的对象javaBean或者JSONObject |
将对象序列化为json字符串 |
| toJSONString(Object object, boolean prettyFormat):String | prettyFormat:是否格式化输出json字符串 |
格式化输出json字符串 |
| toJSONString(Object object, SerializerFeature... features):String | features:序列化额外属性配置,非必填 |
根据指定属性进行序列化 |
| toJSONStringWithDateFormat(Object object, String dateFormat, SerializerFeature... features):String | dateFormat:日期格式(yyyy-MM-dd) |
序列化时格式化日期 |
这些方法中最常用的即为:toJSONString(Object object)
parse
实现了json字符串(
JSONString)>json对象(JSONObject),和json字符串(JSONString)>json对象数组(JSONArray)的转化

| 方法 : 返回值 | 参数说明 | 功能 |
|---|---|---|
| parse(String text):Object | text:json字符串 |
反序列化json字符串 |
parseObject
实现了json字符串(
JSONString)>json对象(JSONObject),和json字符串(JSONString)>Java对象(JavaBean)的转化

| 方法 : 返回值 | 参数说明 | 功能 |
|---|---|---|
| parseObject(String text):JSONObject | text:json字符串 |
反序列化json字符串为Json对象 |
| parseObject(String text, Class clazz):T | clazz:指定反序列化后的类 |
json字符串转java对象 |
| parseObject(String text, TypeReference type, Feature... features):T | type:构造转化类型,features:反序列化额外属性 |
json字符串转java对象 |
parseArray
实现了json字符串(
JSONString)==>json对象数组(JSONArray),和json字符串(JSONString)==>Java对象集合(List`)的转化

| 方法 : 返回值 | 参数说明 | 功能 |
|---|---|---|
| parseArray(String text) :JSONArray | text:json字符串 |
将json字符串反序列化为JSON数组对象 |
| parseArray(String text, Class clazz):List | clazz:指定转化后的类 |
将json字符串反序列化为java对象集合 |
toJSON/toJavaObject

toJSON()实现了Java对象(
JavaBean)==>Json对象(JSONObject)的转换toJavaObject()实现了Json对象(
JSONObject)==>Java对象(JavaBean)的转换
| 方法 : 返回值 | 参数说明 | 功能 |
|---|---|---|
| toJSON(Object javaObject):Object | javaObject:java对象 |
java对象转化为Json对象 |
| toJavaObject(JSON json, Class clazz):T | json:json对象,clazz:要转化的类型 |
json对象转化为java对象 |
代码示例
Student学生类
package com.larscheng.www.jsontest;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.Date;
/**
* 描述:
* 学生类
*
* @author larscheng
* @date 2019/11/19 19:33
*/
@Data
@AllArgsConstructor
public class Student {
private String name;
private int age;
private Date birthday;
}
测试类FastJsonTest.java代码如下:
package com.larscheng.www.jsontest.fastJson;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.larscheng.www.jsontest.Course;
import com.larscheng.www.jsontest.Student;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
* 描述:
* fastJson的api示例
*
* @author larscheng
* @date 2019/11/19 19:37
*/
public class FastJsonTest {
private final static Student LIMING = new Student("liming", 20, new Date());
private final static String LIMING_STR =
"{'age':20,'birthday':1574163958480,'name':'liming'}";
private final static Course MATH = new Course("数学课", "高等代数");
private final static Course CHINESE = new Course("语文课", "大学语文");
private final static List<Course> COURSES = Arrays.asList(MATH, CHINESE);
private final static String COURSES_STR =
"[{'desc':'高等代数','name':'数学课'},{'desc':'大学语文','name':'语文课'}]";
private final static JSONObject LIMING_MAP = new JSONObject();
static {
LIMING_MAP.put("name", "liming");
LIMING_MAP.put("age", 20);
LIMING_MAP.put("birthday", new Date());
}
public static void main(String[] args) {
//############ toJSONString ###############
/*JavaBean--->JSONString*/
System.err.println("JavaBean--->JSONString(默认无格式):");
System.out.println(JSON.toJSONString(LIMING));
System.err.println("JavaBean--->JSONString(带格式):");
System.out.println(JSON.toJSONString(LIMING, true));
System.err.println("JavaBean--->JSONString(日期格式化):");
System.out.println(JSON.toJSONStringWithDateFormat(LIMING, "yyyy-MM-dd") + "\n");
/*JSONObject--->JSONString*/
System.err.println("JSONObject--->JSONString(带格式):");
System.out.println(JSON.toJSONString(LIMING_MAP, true) + "\n");
/*List<JavaBean>--->JSONString*/
System.err.println("List<JavaBean>--->JSONString(默认双引号):");
System.out.println(JSON.toJSONString(COURSES));
System.err.println("List<JavaBean>--->JSONString(单引号):");
System.out.println(JSON.toJSONString(COURSES, SerializerFeature.UseSingleQuotes));
System.err.println("List<JavaBean>--->JSONString(单引号+带格式):");
System.out.println(JSON.toJSONString(COURSES, SerializerFeature.UseSingleQuotes,SerializerFeature.PrettyFormat) + "\n");
//########## parse/parseObject ###################
/*JSONString--->JSONObject*/
System.err.println("JSONString--->JSONObject(parse):");
JSONObject jsonObject1 = (JSONObject) JSON.parse(LIMING_STR);
System.out.println(jsonObject1.toString());
System.err.println("JSONString--->JSONObject(parseObject):");
System.out.println(JSON.parseObject(LIMING_STR).toString() + "\n");
System.err.println("JSONString--->JavaBean:");
Student student1 = JSON.parseObject(LIMING_STR,Student.class);
System.out.println(student1.hashCode()+"\t"+student1.toString());
System.err.println("JSONString--->JavaBean:");
Student student2 = JSON.parseObject(LIMING_STR,new TypeReference<Student>(){});
System.out.println(student2.hashCode()+"\t"+student2.toString());
//########### parse/parseArray ################
/*JSONString--->JSONArray*/
System.err.println("JSONString--->JSONArray(parse):");
JSONArray jsonArray1 = (JSONArray) JSON.parse(COURSES_STR);
System.out.println(jsonArray1.toString());
System.err.println("JSONString--->JSONArray(parseArray):");
System.out.println(JSON.parseArray(COURSES_STR).toString());
System.err.println("JSONString--->List<JavaBean>:");
List<Course> courses1 = JSON.parseArray(COURSES_STR,Course.class);
System.out.println(courses1.hashCode()+"\t"+courses1.toString()+"\n");
//######### toJSON/toJavaObject ################
System.err.println("JavaBean--->JSONObject:");
System.out.println(JSON.toJSON(LIMING));
System.err.println("JSONObject--->JavaBean:");
System.out.println(JSON.toJavaObject(LIMING_MAP,Student.class));
System.out.println(LIMING_MAP.toJavaObject(Student.class));
System.out.println((Student)LIMING_MAP.toJavaObject(new TypeReference<Student>(){}));
System.out.println(LIMING_MAP.toJavaObject(new TypeReference<Student>(){}.getType())+"\n");
}
}
总结
基本常用的方法都进行了代码测试,使用过程中可能会出现混淆的情况,但是只要记住了文中的转换图,相信应该会加深印象。
- 文章作者: LarsCheng
- 文章链接: 本文首发于个人博客:https://www.larscheng.com/
- 发布方式:OpenWrite 最懂你的科技自媒体管理平台
- 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 LarsCheng's Blog!
FastJson中JSONString与各个对象的的转换关系及API示例的更多相关文章
- js 中 json.stringfy()将对象、数组转换成字符串
json.stringfy()将对象.数组转换成字符串 var student = new Object(); student.name = "Lanny"; student.ag ...
- fastjson中对象转化为字符串时过滤某字段
fastjson中对象转化为字符串时过滤某字段,有两种方法: 一.在该字符定义上方添加"@JSONField(serialize=false)"注解: 二.调用含有Property ...
- FastJson中的ObjectMapper对象的使用详解
写在前面:开发中经常用到json和对象的相互转换,下面将列出FastJson中ObjectMapper对象的API的使用 一.maven工程中pom导入<dependency> <g ...
- FastJson中@JSONField注解使用
最近做项目中,使用了json格式在服务器之间进行数据传输.但是发现json格式数据不符合JAVA中的变量定义规则,并且难以理解,因此需要在后台中做二次处理,将数据处理成我们系统中定义的格式. 思路: ...
- FastJson中JSONObject用法及常用方法总结
本文为博主原创,未经允许不得转载: 最近一直有用到解析各种数据,主要是用FastJson进行数据解析,其中一个重要的类为JSONObject,今天有时间,所以进行总结一下: JSONobject是Fa ...
- JavaWeb_(Jar)使用fastjson解析json和序列化对象
菜鸟教程 传送门 JSON官网 传送门 fastjson插件下载 传送门 序列化[百度百科]:序列化 (Serialization)是将对象的状态信息转换为可以存储或传输的形式的过程.在序列化期间,对 ...
- OO中,先有对象还是先有类?
就是问,在面向对象思想里,先有对象还是先有类,乍一看和先有鸡蛋还是先有鸡是一类问题,其实不然!这个问题,在lz考研复试的时候被面试官问过,一模一样,如今又在一个笔试题里看到了类似的题目,眨一下,有人会 ...
- 深入理解Javascript中构造函数和原型对象的区别
在 Javascript中prototype属性的详解 这篇文章中,详细介绍了构造函数的缺点以及原型(prototype),原型链(prototype chain),构造函数(constructor) ...
- js中解析json对象:JSON.parse()用于从一个字符串中解析出json对象, JSON.stringify()用于从一个对象解析出字符串。
JSON.parse()用于从一个字符串中解析出json对象. var str = '{"name":"huangxiaojian","age&quo ...
随机推荐
- Redis集群同步问题
之前被面试官问到:Redis集群中主从数据同步是从库异步读取主库,那么Redis集群其他主与主之间的数据是怎么共享的呢?或者说是怎么同步的? emmmm……当时我就懵逼了,这不是考试范围啊卧槽~只能老 ...
- 【如何让代码变“高级”(一)】-Spring组合注解提升代码维度
原创不易,点个赞
- 【集训Day3 离散化】矩形覆盖
矩形覆盖(planting) [问题描述] 给定在一个平面坐标系上的N(1 <= N <= 100)个矩形区域,这N个矩形可能有相互覆盖的部分.求平面上被所有矩形覆盖的总面积,重复部分只算 ...
- SpringBoot时间参数处理完整解决方案
在JavaWeb程序的开发过程中,接口是前后端对接的主要窗口,而接口参数的接收有时候是一个令人头疼的事情,这其中最困扰程序猿的,应该是时间参数的接收. 比如:设置一个用户的过期时间,前端到底以什么格式 ...
- 痞子衡嵌入式:恩智浦i.MX RTxxx系列MCU启动那些事(1)- Boot简介
大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家介绍的是恩智浦i.MX RTxxx系列MCU的BootROM功能简介. 截止目前为止i.MX RTxxx系列已公布的芯片仅有一款i.MXRT60 ...
- Linux海量数据高并发实时同步架构方案杂谈
不论是Redhat还是CentOS系统,除去从CDN缓存或者数据库优化.动静分离等方面来说,在架构层面上,实 现海量数据高并发实时同步访问概括起来大概可以从以下几个方面去入手,当然NFS的存储也可以是 ...
- 爬虫框架Scrapy入门——爬取acg12某页面
1.安装1.1自行安装python3环境1.2ide使用pycharm1.3安装scrapy框架2.入门案例2.1新建项目工程2.2配置settings文件2.3新建爬虫app新建app将start_ ...
- PHP的array_walk和array_map函数实现数组值UTF-8转GBK编码
在PHP中,array_walk() 和 array_map()两个函数都可以实现对数组中每个值的修改,比如本例就是将数组中所有的值,由UTF-8编码转成GBK编码. 当然,除了这两个函数,也可以用 ...
- [开源] 基于Layui组件封装的后台模版,HG-Layui-UI通用后台管理框架V1.0版
HG框架简介 HG-Layui-UI框架,是基于layui最新版UI搭建的一套通用后台管理框架,借鉴了市面上各大主流框架风格,采用iframe标签页实现,保留了传统开发模式的简单实用性. 为快速开发减 ...
- Python中的Base64编码的加密与解密
Base64 可以干些啥? Base64编码的作用: 由于某些系统中只能使用ASCII字符.Base64就是用来将非ASCII字符的数据转换成ASCII字符的一种方法. 图片(and种子)base64 ...