在Android開發中,咱們Android客戶端若是要和服務器端交互,通常都會採用json數據格式進行交互,FastJson是阿里巴巴工程師開發的一個Json處理工具包,包括「序列化」和「反序列化」兩部分,Fastjson是一個Java語言編寫的高性能功能完善的JSON庫。java
一個JSON庫涉及的最基本功能就是序列化和反序列化。算法
Fastjson支持java bean的直接序列化。你可使用com.alibaba.fastjson.JSON這個類進行序列化和反序列化。fastjson採用首創的算法,將parse的速度提高到極致,超過全部json庫。json
FastJson速度最快,fastjson具備極快的性能,超越任其餘的Java Json parser。服務器
FastJson功能強大,徹底支持Java Bean、集合、Map、日期、Enum,支持範型,支持自省;無依賴。函數
Fastjson API入口類是com.alibaba.fastjson.JSON,經常使用的序列化操做均可以在JSON類上的靜態方法直接完成。工具
使用Fastjson首先在官網下載,而後應用到本身的項目中,下面連接是開源社區的連接:性能
http://www.oschina.net/p/fastjsonurl
1.首先概述一下Fastjson中的常常調用的方法:spa
2 public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject
3 public static final T parseObject(String text, Class clazz); // 把JSON文本parse爲JavaBean
4 public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray
5 public static final List parseArray(String text, Class clazz); //把JSON文本parse成JavaBean集合
6 public static final String toJSONString(Object object); // 將JavaBean序列化爲JSON文本
7 public static final String toJSONString(Object object, boolean prettyFormat); // 將JavaBean序列化爲帶格式的JSON文本
8 public static final Object toJSON(Object javaObject); 將JavaBean轉換爲JSONObject或者JSONArray。
2.如何使用Fastjson.net
1)服務器端使用Fastjson將數據轉換成json字符串
主要使用的函數以下:
2 {
3 String alibabaJson = JSON.toJSONString(value);//此處轉換
4 return alibabaJson;
5 }
服務器端調用此函數執行轉換便可,此處再也不贅述。
2)客戶端將從服務器端獲取到的json字符串轉換爲相應的javaBean,下面給以寫核心的函數例子,供讀者參考:
2 {
3 try
4 {// 獲取HttpURLConnection鏈接對象
5 URL url = new URL(urlStr);
6 HttpURLConnection httpConn = (HttpURLConnection) url
7 .openConnection();
8 // 設置鏈接屬性
9 httpConn.setConnectTimeout(3000);
10 httpConn.setDoInput(true);
11 httpConn.setRequestMethod("GET");
12 // 獲取相應碼
13 int respCode = httpConn.getResponseCode();
14 if (respCode == 200)
15 {
16 return ConvertStream2Json(httpConn.getInputStream());
17 }
18 }
19 catch (MalformedURLException e)
20 {
21 // TODO Auto-generated catch block
22 e.printStackTrace();
23 }
24 catch (IOException e)
25 {
26 // TODO Auto-generated catch block
27 e.printStackTrace();
28 }
29 return "";
30 }
31 private static String ConvertStream2Json(InputStream inputStream)
32 {
33 String jsonStr = "";
34 // ByteArrayOutputStream至關於內存輸出流
35 ByteArrayOutputStream out = new ByteArrayOutputStream();
36 byte[] buffer = new byte[1024];
37 int len = 0;
38 // 將輸入流轉移到內存輸出流中
39 while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
40 {
41 out.write(buffer, 0, len);
42 }
43 // 將內存流轉換爲字符串
44 jsonStr = new String(out.toByteArray());
45 return jsonStr;
46 }
3)使用泛型獲取javaBean(核心函數)
2 T t = null;
3 t = JSON.parseObject(jsonString, cls);
4 return t;
5 }
6 public static List getPersons(String jsonString, Class cls) {
7 List list = new ArrayList();
8 list = JSON.parseArray(jsonString, cls);
9 return list;
10 }