該文章主要介紹com.alibaba.fastjson的使用。java
首先建立maven工程,導入fastjson.挑個熱度高的版本就行了。json
首先考慮下,咱們一般何時會使用序列化和反序列化:數組
1.將java對象序列化爲一個JSON字符串app
// 將javaBean轉換成json字符串,有一個Student對象stu1 //Student對象直接輸出爲Student [id=20180306, name=Claire, age=18, gender=girl] String stuToJsonStr1 = JSON.toJSONString(stu1); System.out.println("Student的一個對象經過 JSON.toJSONString轉換成字符串格式"+stuToJsonStr1); String stuToJsonStr2 = JSONObject.toJSONString(stu1); System.out.println("Student的一個對象經過JSONObject.toJSONString轉換成字符串格式"+stuToJsonStr2); String stuToJsonStr3 = JSONArray.toJSONString(stu1); System.out.println("Student的一個對象經過JSONArray.toJSONString轉換成字符串格式"+stuToJsonStr3);
2.將java對象序列化爲一個Json對象maven
// 將javaBean轉換成Json對象,生成的對象,其中字段順序並不與Javabean字段相同 //有一個Student對象stu1 //Student對象直接輸出爲Student [id=20180306, name=Claire, age=18, gender=girl] Object obj1 = JSONObject.toJSON(stu1); if (obj1 instanceof JSON) { System.out.println("student對象(id,name,age,gender)經過JSONObject.toJSON轉換成json對象,是無序的"+obj1); } Object obj2 = JSON.toJSON(stu1); if (obj1 instanceof JSON) { System.out.println("student對象(id,name,age,gender)經過JSON.toJSON轉換成json對象,是無序的"+obj2); } Object obj3 = JSONArray.toJSON(stu1); if (obj1 instanceof JSON) { System.out.println("student對象(id,name,age,gender)經過JSONArray.toJSON轉換成json對象,是無序的"+obj3); }
3.將Json對象寫到某文件中ide
// 把序列化以後的json對象寫到指定文件中 //文件顯示爲{"gender":"girl","name":"Claire","id":20180306,"age":18} JSON.writeJSONString(new FileWriter("C:\\your\\file\\path\\fileName.txt"), obj3);
4.將JSON字符串轉換成JSON對象函數
// 把json字符串轉換成json對象 String jsonString = "{\"age\":18,\"gender\":\"girl\",\"id\":20180306,\"name\":\"Claire\"}"; Object obj4 = JSONArray.parse(jsonString); System.out.println("用JSONArray.parse將json字符串轉化爲json對象" + obj4); //System.out.println(JSONArray.parseArray(jsonString));這裏會報錯的,由於這個方法只能轉換帶【】的 System.out.println(JSONObject.parseObject(jsonString));
5.將JSON對象轉換成Java對象、JSON字符串轉換成java對象ui
// json對象轉換成javaBean
//下面是將JSON對象轉換成student對象,若是將前面的json對象換成JSON字符串,就是將json字符串轉換成student對象了
Student stu2 = JSON.toJavaObject((JSON) obj4, Student.class); System.out.println("用JSON.toJavaObject將Jason對象轉換成java對象" + stu2); System.out.println( "用JSONArray.toJavaObject將Jason對象轉換成java對象" + JSONArray.toJavaObject((JSON) obj4, Student.class)); System.out.println( "用JSONObject.toJavaObject將Jason對象轉換成java對象" + JSONObject.toJavaObject((JSON) obj4, Student.class));
6.對象數組轉換成json對象this
// 對象數組轉換成json對象 Student stuobj1 = new Student(10001, "leafly", 19, "xinjiboy"); Student stuobj2 = new Student(10002, "Claire", 19, "beauifyGirl"); Student[] stuArry = { stuobj1, stuobj2 }; String jsonObjStr = JSONObject.toJSONString(stuArry); System.out.println("對象數組轉換成json字符串" + jsonObjStr);// [{"age":19,"gender":"xinjiboy","id":10001,"name":"leafly"},{"age":19,"gender":"beauifyGirl","id":10002,"name":"Claire"}] String jString = JSON.toJSONString(stu1); System.out.println("單個對象轉換成json字符串" + jString);//單個對象轉換成json字符串{"age":18,"gender":"girl","id":20180306,"name":"Claire"}
介紹下JSONObject:spa
其底層是Map<String, Object>。因此,能夠經過下面方式來遍歷咱們JSONObject中的全部元素
// jsonObject的結構解析,底層是map Object jsonObject2 = JSON.toJSON(stu1); JSONObject jsonobj = (JSONObject) jsonObject2; Map<String, Object> map = jsonobj.getInnerMap(); Set<String> mapKeys = map.keySet(); for (String mapKey : mapKeys) { System.out.println("getInnerMap的方法來遍歷" + mapKey + "---" + map.get(mapKey)); } // 第二種遍歷方法,entrySet是保存了map(即:jsonObject)的set集合 // public Set<Map.Entry<String, Object>> entrySet() {} Iterator<Entry<String, Object>> it = jsonobj.entrySet().iterator(); while (it.hasNext()) { Entry<String, Object> entry = it.next(); System.out.println("entrySet的方法2來遍歷" + entry.getKey() + "----" + entry.getValue()); }
介紹下JSONArray:
其底層是個list,能夠經過下面方式來遍歷元素
// jsonArray的結構解析,底層是ArrayList // JSONArray jsonArray =(JSONArray)JSONArray.toJSON(stu1); String jsonObjectStr1 = "[{'aa':'claire'},{'bb':'leaf'},{'cc':'黎明'},{'dd':'郭富城'}]"; //JSONArray.ParseArray只能解析[]這種類型的([{'aa':'claire'},{'bb':'leaf'},{'cc':'黎明'},{'dd':'郭富城'}]) JSONArray jsonArray = JSONArray.parseArray(jsonObjectStr1); Iterator<Object> it2 = jsonArray.iterator(); for (Object object : jsonArray) { System.out.println("遍歷jsonArray" + object); }
除了上述基本語法以外,咱們還常常會遇到一個問題:對象A中的某個字段aa,並不想序列化它。此時,有5種解決方式。你們能夠了解下:
package com.claire.jing; import java.util.ArrayList; import java.util.List; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.PropertyFilter; import com.alibaba.fastjson.serializer.SerializeFilter; import com.alibaba.fastjson.serializer.SimplePropertyPreFilter; public class TestPropertyFilter { //第三種設置個別字段不參數化的方式:建立一個fastJson的攔截器 public static void main(String[] args) { PropertyFilter filter = new PropertyFilter() { public boolean apply(Object object, String name, Object value) { //攔截掉gender 字段 if (name.equals("gender")) { return false; }else { return true; } } }; //建立pet對象 Pet pet =new Pet(10001, "cat-mimi", "boy"); //將pet對象轉換成JSON字符串,輸出結果爲{"id":10001,"name":"cat-mimi"} String jsonString = JSON.toJSONString(pet,filter); // System.out.println(jsonString); //第四種設置個別字段不參數化的方式(想要哪些字段參數化,將其列出來) SimplePropertyPreFilter simpleFilter =new SimplePropertyPreFilter(Pet.class, "id","gender"); //將pet對象轉換成JSON字符串,輸出結果爲:{"gender":"boy","id":10001} //System.out.println(JSONArray.toJSONString(pet, simpleFilter)); //第五種設置個別字段不參數化的方式,深層次過濾 //當一個類A中含有其餘類B的引用時,若是要參數化過濾某字段時,就須要深層次過濾(其實就是過濾A又過濾B) //先建立2個Pet Pet cat = new Pet(100001, "cat-mimi2", "boy"); Pet dog = new Pet(100002, "dog-wangwang", "girl"); List<Pet> petList = new ArrayList<Pet>(); petList.add(cat); petList.add(dog); //建立一個PetOwner PetOwner owner = new PetOwner(20001, petList); String petOwnerJsonStr1 = JSON.toJSONString(owner); System.out.println(petOwnerJsonStr1); SimplePropertyPreFilter simpleFilter1 = new SimplePropertyPreFilter(PetOwner.class,"id","ownPets"); SimplePropertyPreFilter simpleFilter2 = new SimplePropertyPreFilter(Pet.class,"name","gender"); //建立一個SerializeFilter的數組,由於後面轉換的時候,想要傳入多個SimplePropertyPreFilter必須將其組織成數組 SerializeFilter[] filters = {simpleFilter1,simpleFilter2}; //將PetOwner對象轉換成Json字符串 String petOwnerJsonStr = JSON.toJSONString(owner, filters); System.out.println(petOwnerJsonStr); } } class PetOwner{ int id; List<Pet> ownPets; // public int getId() { return id; } public void setId(int id) { this.id = id; } public List<Pet> getOwnPets() { return ownPets; } public void setOwnPets(List<Pet> ownPets) { this.ownPets = ownPets; } // @Override public String toString() { StringBuffer buffer = new StringBuffer(); for (Pet pet : ownPets) { buffer.append("PetOwner [id=" + id + ", pet=" + pet + "]") ; } return buffer.toString(); } // public PetOwner(int id, List<Pet> ownPets) { super(); this.id = id; this.ownPets = ownPets; } public PetOwner() { } } class Pet{ private int id; private String name; private String gender; //第一種防止字段序列化的方法:加上transient字段 private transient String kind; //第二種防止字段序列化的方法:註解 @JSONField(serialize=false) private String length; //getter setter public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } // public Pet(int id, String name, String gender) { super(); this.id = id; this.name = name; this.gender = gender; } public Pet() { } // @Override public String toString() { return "Pet [id=" + id + ", name=" + name + ", gender=" + gender + "]"; } }
有時須要將咱們的配置文件讀成JSON對象,下面是實現方法:
package com.claire.jing; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import javax.sound.midi.Soundbank; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; public class ReadJsonProToJsonObj { public static void main(String[] args) throws IOException, InterruptedException { //建立流懟到配置文件上 BufferedReader reader = new BufferedReader(new FileReader("C:\\your\\file\\path\\fileName.txt")); //一行一行讀取配置文件, StringBuffer buffer = new StringBuffer(1024*10); String temp =null; while ((temp = reader.readLine()) != null ) { buffer.append(temp); } String proStr = buffer.toString(); reader.close(); String[] jsonStrs = proStr.split(";"); for (String jsonStr : jsonStrs) { jsonStr.trim(); if (jsonStr.startsWith("[")&&jsonStr.endsWith("]")) { JSONArray array = JSONArray.parseArray(jsonStr); System.out.println(array);
//轉換成JSON對象的時候,是須要時間的,若是這個還沒轉化完就去轉換別的了,就會報錯。這裏給他10S鍾去轉換,時間足夠了。 Thread.sleep(10000); } else if (jsonStr.startsWith("{") && jsonStr.endsWith("}")) { Object obj2 = JSON.parse(jsonStr); System.out.println(obj2); Thread.sleep(10000); } } } }
特別注意:須要序列化類A的對象,那麼類A中必需要Getter setter方法,必須有無參構造函數。否則就序列化不出來啦!!