JSON協議使用方便,愈來愈流行,JSON的處理器有不少,這裏我介紹一下FastJson,FastJson是阿里的開源框架,被很多企業使用,是一個極其優秀的Json框架,Github地址: FastJsonjava
1.FastJson數度快,不管序列化和反序列化,都是當之無愧的fast
2.功能強大(支持普通JDK類包括任意Java Bean Class、Collection、Map、Date或enum)
3.零依賴(沒有依賴其它任何類庫)git
FastJson對於json格式字符串的解析主要用到了下面三個類:
1.JSON:fastJson的解析器,用於JSON格式字符串與JSON對象及javaBean之間的轉換
2.JSONObject:fastJson提供的json對象
3.JSONArray:fastJson提供json數組對象github
首先定義三個json格式的字符串json
//json字符串-簡單對象型 private static final String JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";
{ "studentName": "lily", "studentAge": 12 }
//json字符串-數組類型 private static final String JSON_ARRAY_STR = "[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]";
[ { "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}]}";
{ "teacherName": "crystall", "teacherAge": 27, "course": { "courseName": "english", "code": 1270 }, "students": [ { "studentName": "lily", "studentAge": 12 }, { "studentName": "lucy", "studentAge": 15 } ] }
/** * 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); }
/** * 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); }