fastjson简介

Fastjson是一个Java语言编写的高性能功能完善的JSON库。它采用一种“假定有序快速匹配”的算法,把JSON Parse的性能提升到极致,是目前Java语言中最快的JSON库。Fastjson接口简单易用,已经被广泛使用在缓存序列化、协议交互、Web输出、Android客户端等多种应用场景

1.前言

1.1.FastJson的介绍:

JSON协议使用方便,越来越流行,JSON的处理器有很多,这里我介绍一下FastJson,FastJson是阿里的开源框架,被不少企业使用,是一个极其优秀的Json框架,Github地址: ​​FastJson​

1.2.FastJson的特点:

1.FastJson数度快,无论序列化和反序列化,都是当之无愧的fast 

2.功能强大(支持普通JDK类包括任意Java Bean Class、Collection、Map、Date或enum) 

3.零依赖(没有依赖其它任何类库)

1.3.FastJson的简单说明:

FastJson对于json格式字符串的解析主要用到了下面三个类: 

1.JSON:fastJson的解析器,用于JSON格式字符串与JSON对象及javaBean之间的转换 

2.JSONObject:fastJson提供的json对象 

3.JSONArray:fastJson提供json数组对象


还在迷茫和彷徨吗,快上车,老司机带你飞!


2.FastJson的用法

首先定义三个json格式的字符串

//json字符串-简单对象型
private static final String JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";

//json字符串-数组类型
private static final String JSON_ARRAY_STR = "[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]";

//复杂格式json字符串
private static final String COMPLEX_JSON_STR = "{\"teacherName\":\"crystall\",\"teacherAge\":27,\"course\":{\"courseName\":\"english\",\"code\":1270},\"students\":[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]}";

2.1.JSON格式字符串与JSON对象之间的转换

2.1.1.json字符串-简单对象型与JSONObject之间的转换

/**
* json字符串-简单对象型到JSONObject的转换
*/
@Test
public void testJSONStrToJSONObject() {

JSONObject jsonObject = JSONObject.parseObject(JSON_OBJ_STR);

System.out.println("studentName: " + jsonObject.getString("studentName") + ":" + " studentAge: "
+ jsonObject.getInteger("studentAge"));

}

/**
* JSONObject到json字符串-简单对象型的转换
*/
@Test
public void testJSONObjectToJSONStr() {

//已知JSONObject,目标要转换为json字符串
JSONObject jsonObject = JSONObject.parseObject(JSON_OBJ_STR);
// 第一种方式
String jsonString = JSONObject.toJSONString(jsonObject);

// 第二种方式
//String jsonString = jsonObject.toJSONString();
System.out.println(jsonString);
}

2.1.2.json字符串(数组类型)与JSONArray之间的转换

/**
* json字符串-数组类型到JSONArray的转换
*/
@Test
public void testJSONStrToJSONArray() {

JSONArray jsonArray = JSONArray.parseArray(JSON_ARRAY_STR);

//遍历方式1
int size = jsonArray.size();
for (int i = 0; i < size; i++) {

JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println("studentName: " + jsonObject.getString("studentName") + ":" + " studentAge: "
+ jsonObject.getInteger("studentAge"));
}

//遍历方式2
for (Object obj : jsonArray) {

JSONObject jsonObject = (JSONObject) obj;
System.out.println("studentName: " + jsonObject.getString("studentName") + ":" + " studentAge: "
+ jsonObject.getInteger("studentAge"));
}
}

/**
* JSONArray到json字符串-数组类型的转换
*/
@Test
public void testJSONArrayToJSONStr() {

//已知JSONArray,目标要转换为json字符串
JSONArray jsonArray = JSONArray.parseArray(JSON_ARRAY_STR);
//第一种方式
String jsonString = JSONArray.toJSONString(jsonArray);

// 第二种方式
//String jsonString = jsonArray.toJSONString(jsonArray);
System.out.println(jsonString);
}

2.1.3.复杂json格式字符串与JSONObject之间的转换

/**
* 复杂json格式字符串到JSONObject的转换
*/
@Test
public void testComplexJSONStrToJSONObject() {

JSONObject jsonObject = JSONObject.parseObject(COMPLEX_JSON_STR);

String teacherName = jsonObject.getString("teacherName");
Integer teacherAge = jsonObject.getInteger("teacherAge");

System.out.println("teacherName: " + teacherName + " teacherAge: " + teacherAge);

JSONObject jsonObjectcourse = jsonObject.getJSONObject("course");
//获取JSONObject中的数据
String courseName = jsonObjectcourse.getString("courseName");
Integer code = jsonObjectcourse.getInteger("code");

System.out.println("courseName: " + courseName + " code: " + code);

JSONArray jsonArraystudents = jsonObject.getJSONArray("students");

//遍历JSONArray
for (Object object : jsonArraystudents) {

JSONObject jsonObjectone = (JSONObject) object;
String studentName = jsonObjectone.getString("studentName");
Integer studentAge = jsonObjectone.getInteger("studentAge");

System.out.println("studentName: " + studentName + " studentAge: " + studentAge);
}
}

/**
* 复杂JSONObject到json格式字符串的转换
*/
@Test
public void testJSONObjectToComplexJSONStr() {

//复杂JSONObject,目标要转换为json字符串
JSONObject jsonObject = JSONObject.parseObject(COMPLEX_JSON_STR);

//第一种方式
//String jsonString = JSONObject.toJSONString(jsonObject);

//第二种方式
String jsonString = jsonObject.toJSONString();
System.out.println(jsonString);

}

2.2.JSON格式字符串与javaBean之间的转换

2.2.1.json字符串-简单对象型与javaBean之间的转换

/**
* json字符串-简单对象到JavaBean之间的转换
*/
@Test
public void testJSONStrToJavaBeanObj() {

//第一种方式
JSONObject jsonObject = JSONObject.parseObject(JSON_OBJ_STR);

String studentName = jsonObject.getString("studentName");
Integer studentAge = jsonObject.getInteger("studentAge");

//Student student = new Student(studentName, studentAge);

//第二种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
//Student student = JSONObject.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {});

//第三种方式,使用Gson的思想
Student student = JSONObject.parseObject(JSON_OBJ_STR, Student.class);

System.out.println(student);
}

/**
* JavaBean到json字符串-简单对象的转换
*/
@Test
public void testJavaBeanObjToJSONStr() {

Student student = new Student("lily", 12);
String jsonString = JSONObject.toJSONString(student);
System.out.println(jsonString);
}

2.2.2.json字符串-数组类型与javaBean之间的转换

/**
* json字符串-数组类型到JavaBean_List的转换
*/
@Test
public void testJSONStrToJavaBeanList() {

//第一种方式
JSONArray jsonArray = JSONArray.parseArray(JSON_ARRAY_STR);

//遍历JSONArray
List<Student> students = new ArrayList<Student>();
Student student = null;
for (Object object : jsonArray) {

JSONObject jsonObjectone = (JSONObject) object;
String studentName = jsonObjectone.getString("studentName");
Integer studentAge = jsonObjectone.getInteger("studentAge");

student = new Student(studentName,studentAge);
students.add(student);
}

System.out.println("students: " + students);


//第二种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
List<Student> studentList = JSONArray.parseObject(JSON_ARRAY_STR, new TypeReference<ArrayList<Student>>() {});
System.out.println("studentList: " + studentList);

//第三种方式,使用Gson的思想
List<Student> studentList1 = JSONArray.parseArray(JSON_ARRAY_STR, Student.class);
System.out.println("studentList1: " + studentList1);

}

/**
* JavaBean_List到json字符串-数组类型的转换
*/
@Test
public void testJavaBeanListToJSONStr() {

Student student = new Student("lily", 12);
Student studenttwo = new Student("lucy", 15);

List<Student> students = new ArrayList<Student>();
students.add(student);
students.add(studenttwo);

String jsonString = JSONArray.toJSONString(students);
System.out.println(jsonString);

}

2.2.3.复杂json格式字符串与与javaBean之间的转换

/**
* 复杂json格式字符串到JavaBean_obj的转换
*/
@Test
public void testComplexJSONStrToJavaBean(){

//第一种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
Teacher teacher = JSONObject.parseObject(COMPLEX_JSON_STR, new TypeReference<Teacher>() {});
System.out.println(teacher);

//第二种方式,使用Gson思想
Teacher teacher1 = JSONObject.parseObject(COMPLEX_JSON_STR, Teacher.class);
System.out.println(teacher1);
}

/**
* 复杂JavaBean_obj到json格式字符串的转换
*/
@Test
public void testJavaBeanToComplexJSONStr(){

//已知复杂JavaBean_obj
Teacher teacher = JSONObject.parseObject(COMPLEX_JSON_STR, new TypeReference<Teacher>() {});
String jsonString = JSONObject.toJSONString(teacher);
System.out.println(jsonString);
}

2.3.javaBean与json对象间的之间的转换

2.3.1.简单javaBean与json对象之间的转换

/**
* 简单JavaBean_obj到json对象的转换
*/
@Test
public void testJavaBeanToJSONObject(){

//已知简单JavaBean_obj
Student student = new Student("lily", 12);

//方式一
String jsonString = JSONObject.toJSONString(student);
JSONObject jsonObject = JSONObject.parseObject(jsonString);
System.out.println(jsonObject);

//方式二
JSONObject jsonObject1 = (JSONObject) JSONObject.toJSON(student);
System.out.println(jsonObject1);
}

/**
* 简单json对象到JavaBean_obj的转换
*/
@Test
public void testJSONObjectToJavaBean(){

//已知简单json对象
JSONObject jsonObject = JSONObject.parseObject(JSON_OBJ_STR);

//第一种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
Student student = JSONObject.parseObject(jsonObject.toJSONString(), new TypeReference<Student>() {});
System.out.println(student);

//第二种方式,使用Gson的思想
Student student1 = JSONObject.parseObject(jsonObject.toJSONString(), Student.class);
System.out.println(student1);
}

2.3.2.JavaList与JsonArray之间的转换

/**
* JavaList到JsonArray的转换
*/
@Test
public void testJavaListToJsonArray() {

//已知JavaList
Student student = new Student("lily", 12);
Student studenttwo = new Student("lucy", 15);

List<Student> students = new ArrayList<Student>();
students.add(student);
students.add(studenttwo);

//方式一
String jsonString = JSONArray.toJSONString(students);
JSONArray jsonArray = JSONArray.parseArray(jsonString);
System.out.println(jsonArray);

//方式二
JSONArray jsonArray1 = (JSONArray) JSONArray.toJSON(students);
System.out.println(jsonArray1);
}

/**
* JsonArray到JavaList的转换
*/
@Test
public void testJsonArrayToJavaList() {

//已知JsonArray
JSONArray jsonArray = JSONArray.parseArray(JSON_ARRAY_STR);

//第一种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
ArrayList<Student> students = JSONArray.parseObject(jsonArray.toJSONString(),
new TypeReference<ArrayList<Student>>() {});

System.out.println(students);

//第二种方式,使用Gson的思想
List<Student> students1 = JSONArray.parseArray(jsonArray.toJSONString(), Student.class);
System.out.println(students1);
}

2.3.3.复杂JavaBean_obj与json对象之间的转换

/**
* 复杂JavaBean_obj到json对象的转换
*/
@Test
public void testComplexJavaBeanToJSONObject() {

//已知复杂JavaBean_obj
Student student = new Student("lily", 12);
Student studenttwo = new Student("lucy", 15);

List<Student> students = new ArrayList<Student>();
students.add(student);
students.add(studenttwo);
Course course = new Course("english", 1270);

Teacher teacher = new Teacher("crystall", 27, course, students);

//方式一
String jsonString = JSONObject.toJSONString(teacher);
JSONObject jsonObject = JSONObject.parseObject(jsonString);
System.out.println(jsonObject);

//方式二
JSONObject jsonObject1 = (JSONObject) JSONObject.toJSON(teacher);
System.out.println(jsonObject1);

}

/**
* 复杂json对象到JavaBean_obj的转换
*/
@Test
public void testComplexJSONObjectToJavaBean() {

//已知复杂json对象
JSONObject jsonObject = JSONObject.parseObject(COMPLEX_JSON_STR);

//第一种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
Teacher teacher = JSONObject.parseObject(jsonObject.toJSONString(), new TypeReference<Teacher>() {});
System.out.println(teacher);

//第二种方式,使用Gson的思想
Teacher teacher1 = JSONObject.parseObject(jsonObject.toJSONString(), Teacher.class);
System.out.println(teacher1);
}

3.源码

本篇博客的源码都在我的Github上,​​FastJsonDemo​​,欢迎大家Fork and Star!

Maven引入

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>fastjson</artifactId>

<version>1.2.37</version>

</dependency>


常用api

1. 将对象序列化成json字符串

String com.alibaba.fastjson.JSON.toJSONString(Object object)

2. 将json字符串反序列化成对象

<T> Project com.alibaba.fastjson.JSON.parseObject(String text, Class<T> clazz)

3. 将json字符串反序列化成JSON对象

JSONObject com.alibaba.fastjson.JSON.parseObject(String text)

4.根据key 得到json中的json数组

JSONArray com.alibaba.fastjson.JSONObject.getJSONArray(String key)

5. 根据下标拿到json数组的json对象

JSONObject com.alibaba.fastjson.JSONArray.getJSONObject(int index)

6.. 根据key拿到json的字符串值

String com.alibaba.fastjson.JSONObject.getString(String key)

7. 根据key拿到json的int值

int com.alibaba.fastjson.JSONObject.getIntValue(String key)

8. 根据key拿到json的boolean值

boolean com.alibaba.fastjson.JSONObject.getBooleanValue(String key)

实例说明

Project类

com.alibaba的fastjson简介_json对象

package com.json;  import java.util.List;  public class Project {     String pjName;     boolean waibao;     public boolean isWaibao() {         return waibao;     }     public void setWaibao(boolean waibao) {         this.waibao = waibao;     }     List<Factory> l_factory;     //List<Worker> worker;     public String getPjName() {         return pjName;     }     public void setPjName(String pjName) {         this.pjName = pjName;     }     public List<Factory> getL_factory() {         return l_factory;     }     public void setL_factory(List<Factory> l_factory) {         this.l_factory = l_factory;     }       }

com.alibaba的fastjson简介_json对象

Factory类

com.alibaba的fastjson简介_json对象

package com.json;  import java.util.List;  public class Factory {      String fcName;     List<Worker> l_worker;     public String getFcName() {         return fcName;     }     public void setFcName(String fcName) {         this.fcName = fcName;     }     public List<Worker> getL_worker() {         return l_worker;     }     public void setL_worker(List<Worker> l_worker) {         this.l_worker = l_worker;     }      }

com.alibaba的fastjson简介_json对象

Worker类

com.alibaba的fastjson简介_json对象

package com.json;  public class Worker {      String name;     String sex;     int age;     public int getAge() {         return age;     }     public void setAge(int age) {         this.age = age;     }     public String getName() {         return name;     }     public void setName(String name) {         this.name = name;     }     public String getSex() {         return sex;     }     public void setSex(String sex) {         this.sex = sex;     }      }

com.alibaba的fastjson简介_json对象

测试类

com.alibaba的fastjson简介_json对象

package com.json;  import java.util.ArrayList; import java.util.List;  import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject;  public class TestFastJson {      public static void main(String args[]) {         TestFastJson tfj = new TestFastJson();         Project prj = tfj.init();         String json= tfj.getJsonString(prj);         System.out.println("json="+json);         //json={"l_factory":[{"fcName":"东软","l_worker":[{"age":30,"name":"乔佳飞","sex":"男"},{"age":25,"name":"李帅飞","sex":"女"}]},{"fcName":"亚信","l_worker":[{"age":26,"name":"王新峰","sex":"男"},{"age":0}]}],"pjName":"接口自动化","waibao":true}         System.out.println("waibao="+tfj.getJsonValueObj(json, "waibao", Boolean.class));         //waibao=true         JSONArray array = (JSONArray) tfj.getJsonValueObj(json, "l_factory", JSONArray.class);         System.out.println("array="+array.toString());         //array=[{"fcName":"东软","l_worker":[{"sex":"男","name":"乔佳飞","age":30},{"sex":"女","name":"李帅飞","age":25}]},{"fcName":"亚信","l_worker":[{"sex":"男","name":"王新峰","age":26},{"age":0}]}]         String jsonArr = tfj.getJsonArrayValue(array, 0, "fcName");         System.out.println("fcName="+jsonArr);         //fcName=东软         JSONArray array2 = tfj.getJsonArrayValueIsArray(array, 0, "l_worker");         System.out.println("array2="+array2.toString());         //array2=[{"sex":"男","name":"乔佳飞","age":30},{"sex":"女","name":"李帅飞","age":25}]         String json2 = tfj.getJsonArrayValue(array2, 0);         System.out.println("json2="+json2);         //json2={"sex":"男","name":"乔佳飞","age":30}                  /*以下输出         name=乔佳飞         sex=男         age=30         jsonArr2=男           * */         System.out.println("name="+tfj.getJsonValueObj(json2, "name", String.class));         System.out.println("sex="+tfj.getJsonValueObj(json2, "sex", String.class));         System.out.println("age="+tfj.getJsonValueObj(json2, "age", Integer.class));                  String jsonArr2 = tfj.getJsonArrayValue(array2, 0, "sex");         System.out.println("jsonArr2="+jsonArr2);                  /*以下输出          接口自动化         东软         乔佳飞          */         System.out.println(tfj.getJsonValue(json));         System.out.println(tfj.getJsonValue(json,"l_factory"));         System.out.println(tfj.getJsonValue(json,"l_factory","l_worker"));              }     public static void main1(String args[]) {         TestFastJson tfj = new TestFastJson();         Project prj = tfj.init();         String json= tfj.getJsonString(prj);         prj.setPjName("序列化后修改pjname");         System.out.println(prj.getPjName());//序列化后修改pjname         Project po = JSON.parseObject(json,Project.class);         System.out.println(po.getPjName());//接口自动化     }          public void tt(Class clazz) {         System.out.println(clazz.getSimpleName());         if(clazz.getName().equals("String")) {             System.out.println("stringllala");         }     }     public Project init() {         Project pj = new Project();         Factory ft1 = new Factory();         Factory ft2 = new Factory();         Worker wk1 = new Worker();         wk1.setName("乔佳飞");         wk1.setSex("男");         wk1.setAge(30);                  Worker wk2 = new Worker();         wk2.setName("李帅飞");         wk2.setSex("女");         wk2.setAge(25);                  Worker wk3 = new Worker();         wk3.setName("魏晓博");         wk3.setSex("男");         wk3.setAge(27);                  Worker wk4 = new Worker();         wk3.setName("王新峰");         wk3.setSex("男");         wk3.setAge(26);                  List<Worker> workers1 = new ArrayList<Worker>();         workers1.add(wk1);         workers1.add(wk2);                  List<Worker> workers2 = new ArrayList<Worker>();         workers2.add(wk3);         workers2.add(wk4);                  ft1.setFcName("东软");         ft1.setL_worker(workers1);                  ft2.setFcName("亚信");         ft2.setL_worker(workers2);          List<Factory> factorys = new ArrayList<Factory>();         factorys.add(ft1);         factorys.add(ft2);                  pj.setPjName("接口自动化");         pj.setWaibao(true);         pj.setL_factory(factorys);                  return pj;     }          /**      *       * 将对象转换成json      * */     public String getJsonString(Object obj) {                 String json= JSON.toJSONString(obj);         return json;     }          /**      * 根据key得到json的value      * */     public String getJsonValue(String json) {         JSONObject jo = JSON.parseObject(json);         String value = jo.getString("pjName");         return value;     }          /**      * 根据key得到json的集合      * */     public JSONArray getJsonArray(String json, String key) {         JSONObject jo = JSON.parseObject(json);                  JSONArray array = jo.getJSONArray(key);                  return array;     }          /**      * 根据下标得到json数组的值      * */     public String getJsonArrayValue(JSONArray array, int index) {         JSONObject jo_fc = array.getJSONObject(index);         String json = jo_fc.toJSONString();         return json;     }          /**      * 根据下标得到json数组的值,再根据key得到该值的value,该值类型是String      * */     public String getJsonArrayValue(JSONArray array, int index, String key) {         JSONObject jo_fc = array.getJSONObject(index);         String value = jo_fc.getString(key);         return value;     }     /**      * 根据下标得到json数组的值,再根据key得到该值的value,该值类型是JSONArray      * */     public JSONArray getJsonArrayValueIsArray(JSONArray array, int index, String key) {         JSONObject jo_fc = array.getJSONObject(index);         JSONArray arrayNew = jo_fc.getJSONArray(key);                 return arrayNew;     }     /**      * 根据对象的类型,自动识别获取该对象的值      * */     public Object getJsonValueObj(String json, String key, Class clazz) {         JSONObject jo = JSON.parseObject(json);         if(clazz.getSimpleName().equals("String")) {             String value = jo.getString(key);             return value;         }else if(clazz.getSimpleName().equals("Integer")) {             Integer value = jo.getInteger(key);             return value;         }else if (clazz.getSimpleName().equals("Boolean")) {             Boolean value = jo.getBoolean(key);             return value;         }else if(clazz.getSimpleName().equals("JSONArray")) {             JSONArray array = jo.getJSONArray(key);             return array;         }         else {             return "error, 暂不支持的类型:"+clazz.toString();         }                      }          public String getJsonValue(String json, String key) {         JSONObject jo = JSON.parseObject(json);                          JSONArray array = jo.getJSONArray(key);         JSONObject jo_fc = array.getJSONObject(0);         String value = jo_fc.getString("fcName");         return value;     }          public String getJsonValue(String json, String key, String keyW) {         JSONObject jo = JSON.parseObject(json);                  JSONArray array = jo.getJSONArray(key);         JSONObject jo_fc = array.getJSONObject(0);         JSONArray arrayW = jo_fc.getJSONArray(keyW);         JSONObject jo_wk = arrayW.getJSONObject(0);         String value = jo_wk.getString("name");         int age = jo_wk.getIntValue("age");         //System.out.println(age);         return value;     } }

com.alibaba的fastjson简介_json对象