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類
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;
}
}
Factory類
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;
}
}
Worker類
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;
}
}
測試類
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;
}
}

