Google 的GSON使用詳解

一、 谷歌GSON這個Java類庫可以把Java對象轉換成JSON,也可以把JSON字符串轉換成一個相等的Java對象。Gson支持任意複雜Java對象包括沒有源代碼的對象。
二、Gson解析Json步驟
A、服務器端將數據轉換成json字符串
首先、服務器端項目要導入Gson的jar包到BuiltPath中。(
Gson的jar:http://code.google.com/p/google-gson/ 我們還可以下載gson的幫助文檔)

然後將數據轉爲json字符串,核心函數是:

    public static String createJsonString(Object value)
    {
        Gson gson = new Gson();
        String str = gson.toJson(value);
        return str;
    }

B、客戶端將json字符串轉換爲相應的javaBean
首先客戶端也要導入gson的兩個jar包,json的jar就不需要導入了(因爲android項目中已經集成了json的jar包所以這裏無需導入)
1、客戶端獲取json字符串

public class HttpUtil
{

    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");
            // 獲取相應碼
            int respCode = httpConn.getResponseCode();
            if (respCode == 200)
            {
                return ConvertStream2Json(httpConn.getInputStream());
            }
        }
        catch (MalformedURLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }


    private static String ConvertStream2Json(InputStream inputStream)
    {
        String jsonStr = "";
        // ByteArrayOutputStream相當於內存輸出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        // 將輸入流轉移到內存輸出流中
        try
        {
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
            {
                out.write(buffer, 0, len);
            }
            // 將內存流轉換爲字符串
            jsonStr = new String(out.toByteArray());
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonStr;
    }
}

2、使用泛型獲取javaBean(核心函數)

 public static <T> T getPerson(String jsonString, Class<T> cls) {
        T t = null;
        try {
            Gson gson = new Gson();
            t = gson.fromJson(jsonString, cls);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return t;
    }

public static <T> List<T> getPersons(String jsonString, Class<T> cls) {
        List<T> list = new ArrayList<T>();
        try {
            Gson gson = new Gson();
            list = gson.fromJson(jsonString, new TypeToken<List<cls>>() {
            }.getType());
        } catch (Exception e) {
        }
        return list;
    }
public static List<Map<String, Object>> listKeyMaps(String jsonString) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            Gson gson = new Gson();
            list = gson.fromJson(jsonString,
                    new TypeToken<List<Map<String, Object>>>() {
                    }.getType());
        } catch (Exception e) {
            // TODO: handle exception
        }
        return list;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章