前言

JSON作为一种轻量级的数据交换格式,在我们日常的开发中使用十分广泛,就Java后端的开发工作中,JSON字符串与Java对象之间相互转换是常常遇到的操作。

虽然平时用到的挺多的,但是因为用于JSON处理的包有很多种,每种工具集的功能和使用方式也都不同,很容易在使用时造成混乱。

本文就结合FastJson部分源码,简单整理了下常用的API及其使用示例

本文FastJson版本:1.2.54

转换图

根据FastJson源码大致整理出了这么一张转换图:

可以看到参与转换的对象主要有图中五种:

  1. JSONStringjson字符串
  2. JSONObjectjson对象
  3. JSONArrayjson对象数组
  4. JavaBeanjava对象
  5. Listjava对象集合

转化中用到的方法的方法名有如下几种:

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

总结

基本常用的方法都进行了代码测试,使用过程中可能会出现混淆的情况,但是只要记住了文中的转换图,相信应该会加深印象。



FastJson中JSONString与各个对象的的转换关系及API示例的更多相关文章

  1. js 中 json.stringfy()将对象、数组转换成字符串

    json.stringfy()将对象.数组转换成字符串 var student = new Object(); student.name = "Lanny"; student.ag ...

  2. fastjson中对象转化为字符串时过滤某字段

    fastjson中对象转化为字符串时过滤某字段,有两种方法: 一.在该字符定义上方添加"@JSONField(serialize=false)"注解: 二.调用含有Property ...

  3. FastJson中的ObjectMapper对象的使用详解

    写在前面:开发中经常用到json和对象的相互转换,下面将列出FastJson中ObjectMapper对象的API的使用 一.maven工程中pom导入<dependency> <g ...

  4. FastJson中@JSONField注解使用

    最近做项目中,使用了json格式在服务器之间进行数据传输.但是发现json格式数据不符合JAVA中的变量定义规则,并且难以理解,因此需要在后台中做二次处理,将数据处理成我们系统中定义的格式. 思路: ...

  5. FastJson中JSONObject用法及常用方法总结

    本文为博主原创,未经允许不得转载: 最近一直有用到解析各种数据,主要是用FastJson进行数据解析,其中一个重要的类为JSONObject,今天有时间,所以进行总结一下: JSONobject是Fa ...

  6. JavaWeb_(Jar)使用fastjson解析json和序列化对象

    菜鸟教程 传送门 JSON官网 传送门 fastjson插件下载 传送门 序列化[百度百科]:序列化 (Serialization)是将对象的状态信息转换为可以存储或传输的形式的过程.在序列化期间,对 ...

  7. OO中,先有对象还是先有类?

    就是问,在面向对象思想里,先有对象还是先有类,乍一看和先有鸡蛋还是先有鸡是一类问题,其实不然!这个问题,在lz考研复试的时候被面试官问过,一模一样,如今又在一个笔试题里看到了类似的题目,眨一下,有人会 ...

  8. 深入理解Javascript中构造函数和原型对象的区别

    在 Javascript中prototype属性的详解 这篇文章中,详细介绍了构造函数的缺点以及原型(prototype),原型链(prototype chain),构造函数(constructor) ...

  9. js中解析json对象:JSON.parse()用于从一个字符串中解析出json对象, JSON.stringify()用于从一个对象解析出字符串。

    JSON.parse()用于从一个字符串中解析出json对象. var str = '{"name":"huangxiaojian","age&quo ...

随机推荐

  1. (二)OpenStack---M版---双节点搭建---数据库安装和配置

    ↓↓↓↓↓↓↓↓视频已上线B站↓↓↓↓↓↓↓↓ >>>>>>传送门 本章节只在Controller节点执行 1.安装Mariadb数据库来存储信息 2.NoSQL数 ...

  2. 仿微信 即时聊天工具 - SignalR (一)

    话不多说,先上图 背景: 微信聊天,经常会遇见视频发不了,嗯,还有聊天不方便的问题,于是我就自己买了服务器,部署了一套可以直接在微信打开的网页进行聊天,这样只需要发送个url给朋友,就能聊天了! 由于 ...

  3. 原生线程池这么强大,Tomcat 为何还需扩展线程池?

    前言 Tomcat/Jetty 是目前比较流行的 Web 容器,两者接受请求之后都会转交给线程池处理,这样可以有效提高处理的能力与并发度.JDK 提高完整线程池实现,但是 Tomcat/Jetty 都 ...

  4. 一个null,差点把系统给弄崩溃了

    今天生产上面发现了一个奇异的bug,URL上面会带上一个ID,这个ID是关联别的系统的,类似这种格式 xxx.xxx.xxx.xxx  ,是别的系统自己填写的,我们的URL会带上id=xxx.xxx. ...

  5. 动态规划--最长上升子序列(LIS)的长度

    l例如:对于[3,1,4,2,5],最长上升子序列的长度是3 arr = [3,1,4,5,9,2,6,5,0] def lis(arr): #dp[i]表示第i个位置的值为尾的数组的最长递增子序列的 ...

  6. 基于华为云CSE微服务接口兼容常见问题

    微服务接口兼容常见问题 在进行微服务持续迭代开发的过程中,由于新特性在不停的加入,一些过时的特性在不停的修改,接口兼容问题面临巨大的挑战,特别是在运行环境多版本共存(灰度发布)的情况下.本章节主要描述 ...

  7. 和为k的倍数

    小b喜欢和为K的倍数的序列. 现在有一个长度为n的序列A,请问A有多少个非空连续子序列是小b喜欢的. #include<cstdio> #include<iostream> # ...

  8. solr集群与项目实战

    什么是 SolrCloud : SolrCloud(solr 云)是 Solr 提供的分布式搜索方案,当你需要大规模,容错,分布式索引和检索能力时使用 SolrCloud.当一个系统的索引数据量少的时 ...

  9. [TimLinux] Python nonlocal和global的作用

    1. 执行代码 以下实例都是通过执行以下代码,需要把以下执行代码放在后面实例代码的后面. a = outer_func()print("call a()") a() a() a() ...

  10. numpy sum axis详解

    axis 先看懂numpy.argmax的含义.那么numpy.sum就非常好理解. 看一维的例子. import numpy as np a = np.array([1, 5, 5, 2]) pri ...