FastJson概述與簡單使用
Android開發之FastJson概述與簡單使用
在Android開發中,我們Android客戶端如果要和服務器端交互,一般都會采用json數據格式進行交互,FastJson是阿里巴巴工程師開發的一個Json處理工具包,包括“序列化”和“反序列化”兩部分,Fastjson是一個Java語言編寫的高性能功能完善的JSON庫。
一個JSON庫涉及的最基本功能就是 序列化 和 反序列化 。
Fastjson支持java bean的直接序列化。你可以使用 com.alibaba.fastjson.JSON 這個類進行序列化和反序列化。
fastjson采用獨創的算法,將parse的速度提升到極致,超過所有json庫。
特點:
FastJson速度最快,fastjson具有極快的性能,超越任其他的Java Json parser。
FastJson功能強大,完全支持Java Bean、集合、Map、日期、Enum,支持范型,支持自省;無依賴。
Fastjson API入口類是 com.alibaba.fastjson.JSON ,常用的序列化操作都可以在JSON類上的靜態方法直接完成。
使用Fastjson首先在官網下載,然后應用到自己的項目中,GitHub鏈接:https://github.com/alibaba/fastjson
FastJson 1.2.6直接下載:https://github.com/alibaba/fastjson/archive/1.2.6.zip
1.概述一下Fastjson中的經常調用的方法:
public static final Object parse(String text); //把JSON文本parse為JSONObject或者JSONArraypublic static final JSONObject parseObject(String text); //把JSON文本parse成JSONObject
public static final T parseObject(String text, Class clazz); // 把JSON文本parse為JavaBean
public static final JSONArray parseArray(String text); //把JSON文本parse成JSONArray
public static final List parseArray(String text, Class clazz); //把JSON文本parse成JavaBean集合
public static final String toJSONString(Object object); //將JavaBean序列化為JSON文本
public static final String toJSONString(Object object, boolean prettyFormat); //將JavaBean序列化為帶格式的JSON文本
public static final Object toJSON(Object javaObject); //將JavaBean轉換為JSONObject或者JSONArray</pre>
2.簡單的使用Fastjson
1)服務器端 使用 Fastjson 將數據轉換成json字符串,主要使用的函數如下:
public static String createJsonString(Object value) {String alibabaJson = JSON.toJSONString(value);//此處轉換 return alibabaJson;
}</pre>
服務器端調用此函數執行轉換即可,此處不再贅述。
2)客戶端 將從服務器端獲取到的json字符串 轉換為相應的javaBean,下面獲取Json數據的函數例子,供參考:
//獲取Json數據 public static String getJsonContent(String urlStr) {try { // 獲取HttpURLConnection連接對象 URL url = new URL(urlStr); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); // 設置連接屬性 httpConn.setConnectTimeout(3000); httpConn.setDoInput(true); httpConn.setRequestMethod("GET"); // 獲取相應碼 200表示請求success int respCode = httpConn.getResponseCode(); if (respCode == 200){ //轉換并返回 return convertStream2Json(httpConn.getInputStream()); } }catch (MalformedURLException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } return null; }
private static String convertStream2Json(InputStream inputStream) {
String jsonStr = ""; // ByteArrayOutputStream相當于內存輸出流 ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; // 將輸入流轉移到內存輸出流中 while ((len = inputStream.read(buffer, 0, buffer.length)) != -1){ out.write(buffer, 0, len); } // 將內存流轉換為字符串 jsonStr = new String(out.toByteArray()); return jsonStr; }</pre> <p><br />
</p>
3)使用泛型獲取javaBean,也可像上述所說,Fastjson API入口類是 com.alibaba.fastjson.JSON ,常用的序列化操作都可以直接在調用JSON類上的靜態方法完成,下面再次封裝了一下。
public static T parse2Bean(String jsonString, Class cls) {T t = null; //調用JSON類中的方法,parse為Bean對象 t = JSON.parseObject(jsonString, cls); return t;
} </pre>
出處:http://blog.csdn.net/gao_chun/article/details/39232097