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

用泛型把 JSON 解析收斂成一個類:JsonHelper 設計思路

編輯:關於 Android 程式設計

這段程式碼是我在一家比利時任職期間寫的。當時忙於戶籍調動,只參與了兩個專案便離開了,心裡其實有些感謝與遺憾——公司在職稱申請上給了我全力支持,而我卻沒能回報更多。

回過來說技術。Android 專案裡解析 JSON 是家常飯碗,但每次都要寫一遍 Gson().fromJson(...) 加上各種型別轉換,實在冗長。這裡的做法是用 Java 泛型把「要轉成什麼型別」當成參數傳進來,讓同一個方法服務所有 model。

核心方法

package com.dday.dataaccesslayer.utils.helper;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.dday.dataaccesslayer.utils.StorageServiceFactory;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonHelper {

    public static <T> T getEntityFromJson(String fromJsonStr, Class<T> classOfT)
            throws JSONException {
        GsonBuilder gsonb = new GsonBuilder();
        gsonb.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);

        DateDeserializer ds = new DateDeserializer();
        gsonb.registerTypeAdapter(Date.class, ds);

        Gson gson = gsonb.create();
        JSONObject j = new JSONObject(fromJsonStr);
        return gson.fromJson(j.toString(), classOfT);
    }

    public static <T> T getEntityFromInterStorage(Context context, String jsonFilePath,
                                                 String charset, Class<T> classOfT)
            throws JSONException, FileNotFoundException,
                   UnsupportedEncodingException, IOException {
        String jsonContent = InterStorageHelper.readInternal(context, jsonFilePath, charset);
        return getEntityFromJson(jsonContent, classOfT);
    }

    public static <T> T getEntityFromInterStorage(Context context, String jsonFilePath,
                                                 Class<T> classOfT)
            throws JSONException, FileNotFoundException,
                   UnsupportedEncodingException, IOException {
        return getEntityFromInterStorage(context, jsonFilePath, "UTF-8", classOfT);
    }

    public static <T> T getEntityFromExterPrivateStorage(Context context, String jsonFilePath,
                                                        String charset, Class<T> classOfT)
            throws JSONException, FileNotFoundException,
                   UnsupportedEncodingException, IOException {
        String jsonContent = StorageServiceFactory.getSharedInstance()
                .getExterStorageService(context)
                .getPrivateFile(jsonFilePath, charset);
        return getEntityFromJson(jsonContent, classOfT);
    }

    public static <T> T getEntityFromExterPrivateStorage(Context context, String jsonFilePath,
                                                        Class<T> classOfT)
            throws JSONException, FileNotFoundException,
                   UnsupportedEncodingException, IOException {
        String jsonContent = StorageServiceFactory.getSharedInstance()
                .getExterStorageService(context)
                .getPrivateFile(jsonFilePath, "UTF-8");
        return getEntityFromJson(jsonContent, classOfT);
    }
}

泛型在這裡發揮了什麼作用

關鍵是 <T> T 搭配 Class<T> classOfT 這對組合。呼叫端只要寫:

User user = JsonHelper.getEntityFromJson(jsonStr, User.class);

編譯器就能推斷回傳型別為 User,不必再手動轉型,也不會有型別轉換的執行期風險。這比傳統寫法「回傳 Object 再由呼叫端轉型」安全得多。

幾個設計細節

命名策略:FieldNamingPolicy.UPPER_CAMEL_CASE 讓 JSON 的 user_name 自動對應 Java 欄位 UserName。若後端命名風格特殊,更好的做法是用 @SerializedName 標註在欄位上,語意比全域策略明確。

自訂型別轉換:DateDeserializer 註冊到 GsonBuilder,讓日期字串能正確轉為 Date 物件。JSON 對日期沒有標準格式,這一層轉換幾乎是每個專案都必須自己處理的。

多層載入來源:這個類同時支援從字串、內部儲存空間、外部私有目錄載入,並提供不含 charset 的重載版本預設 UTF-8,讓呼叫端程式碼更簡潔。

本類依賴 Gson 函式庫;其中引用的 DateDeserializer、InterStorageHelper、StorageServiceFactory 等型別屬於專案內其他層級,此處不便提供,僅供參考其中的封裝邏輯。

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