Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 Gson 打通 Java 對象與 JSON 數據的雙向轉換

編輯:關於 Android 程式設計

拜接口時,請求參數要序列化成 JSON,返回結果又要反序列化回對象。手拼字符串顯然不靠譜,Gson 這類庫才是正解。下面用一個完整的例子走一遍:請求參數是 JSON,返回結果也是 JSON。

Activity:起個線程發請求

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
    }

    private void init() {
        new Thread() {
            public void run() {
                GetJsonDataByPost httpJsonPost = new GetJsonDataByPost();
                String[] pathArray = httpJsonPost.getPathArray("dev0003");
                for (int i = 0; i < pathArray.length; i++) {
                    System.out.println(pathArray[i]);
                }
            }
        }.start();
    }
}

網絡請求放在子線程裡,這是 Android 的硬性要求——主線程做網絡操作會直接拋 NetworkOnMainThreadException。

網絡層:POST 發送 JSON

public class GetJsonDataByPost {
    static private String Service_URL = "Your url";
    static private int TIMEOUT = 120 * 1000;
    String mMethodName;

    public String[] getPathArray(String devnum) {
        try {
            mMethodName = "GetPicByUser";
            // 1. 把調用 API 的參數封裝成 JSON
            String jsonParams = JsonUtils.getJsonRequestParams(devnum);
            // 2. 發請求,拿回 JSON 格式的結果
            String jsonResult = getJsonDataByPost(jsonParams);
            // 3. 從結果中取出 pic 數組
            return JsonUtils.getJsonRequestResponse(jsonResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getJsonDataByPost(String json) {
        String result = null;
        try {
            StringEntity entity = new StringEntity(json, HTTP.UTF_8);
            entity.setContentType("application/json");

            DefaultHttpClient client = new DefaultHttpClient();
            client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, TIMEOUT);
            client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, TIMEOUT);
            if (mMethodName == null) {
                return null;
            }

            HttpPost httpPost = new HttpPost(Service_URL + mMethodName);
            httpPost.setEntity(entity);
            HttpResponse response = client.execute(httpPost);

            InputStream inputStream = response.getEntity().getContent();
            StringBuffer buffer = new StringBuffer();
            InputStreamReader inputReader = new InputStreamReader(inputStream);
            BufferedReader bufferReader = new BufferedReader(inputReader);
            String str = new String("");
            while ((str = bufferReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferReader.close();
            result = buffer.toString();
            System.out.println("---> API 的請求結果 result=" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

這裡的關鍵是 setContentType("application/json") 加上 StringEntity,讓服務端知道請求體是 JSON 而不是表單。

Gson 工具類:真正的魔法所在

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

public class JsonUtils {

    // 封裝請求 API 的參數,請求時轉為 JSON
    static class JsonRequestParams {
        String devsn;
        int uploadid;
        float healthScore;
    }

    // 封裝 API 返回的結果,響應時由 JSON 轉為該對象
    static class JsonRequestResult {
        String resultcode;
        int uploadid;
        String[] pics;
        float beat;
        String crtime;
    }

    // 對象 → JSON
    public static String getJsonRequestParams(String devnum) {
        try {
            JsonRequestParams params = new JsonRequestParams();
            params.devsn = devnum;
            params.uploadid = 0;
            params.healthScore = 0.0f;

            Gson gson = new Gson();
            String json = gson.toJson(params);
            System.out.println("---> 封裝後的請求參數 " + json);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // JSON → 對象
    public static String[] getJsonRequestResponse(String ret) {
        try {
            Gson gson = new Gson();
            JsonRequestResult result = gson.fromJson(ret, JsonRequestResult.class);
            if (result.resultcode.contains("ok")) {
                System.out.println("---> resultcode=" + result.resultcode);
                System.out.println("---> beat=" + result.beat);
                System.out.println("---> uploadid=" + result.uploadid);
                System.out.println("---> crtime=" + result.crtime);
                return result.pics;
            }
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Gson 的省心之處就在這裡:字段名與 JSON 的 key 同名,它會自動完成映射,連 String[] 這種數組結構都能直接對應,完全不用手写解析。

布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Everyone"
        android:layout_centerInParent="true" />

</RelativeLayout>

兩點實踐建議

一是字段命名。Gson 默認按字段名精確匹配,如果服務端用下劃線風格(result_code),可以在字段上加 @SerializedName("result_code"),或者構造 Gson 時指定 FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES。

二是解析失敗的處理。示例裡只捕獲了 JsonSyntaxException,實際項目中服務端返回 HTML 錯誤頁、空響應、字段類型不匹配都很常見,最好把異常捕得寬一些,並對關鍵字段做空值判斷,別讓一個髒數據把整個流程帶崩。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved