簡體   English   中英

gson與泛型的正確語法

[英]Proper syntax for gson with generics

我試圖編寫一個可重用的asynctask,在其中定義了Gson應該在asynctask的構造函數中反序列化的類的類型。 之前從未使用過Java Generics,但是我對如何進行操作有些迷茫。 我無法為fromJson方法找出正確的語法。

我收到的錯誤是

Cannot resolve method'fromJson(java.io.InputStream, java.lang.Class<T>)'

完整的AsyncTask ...

public class AsyncGet<T> extends AsyncTask<String,String,ApiResponse> {

    private String TAG = "AsyncGet";
    private HttpURLConnection mConnection;
    private IApiCallback mCallback;
    private Context mContext;
    private Class<T> type;

    public AsyncGet(IApiCallback callback, Class<T> classType, Context context) {
        this.mCallback = callback;
        this.mContext = context;
        this.type = classType;
    }

    @Override
    protected ApiResponse doInBackground(String... uri) {

        try {

            URL url = new URL(uri[0]);
            mConnection = (HttpURLConnection) url.openConnection();
            mConnection.setConnectTimeout(5000);
            mConnection.setReadTimeout(60000);
            mConnection.addRequestProperty("Accept-Encoding", "gzip");
            mConnection.addRequestProperty("Cache-Control", "no-cache");
            mConnection.connect();

            String encoding = mConnection.getContentEncoding();

            InputStream inStream;
            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                inStream = new GZIPInputStream(mConnection.getInputStream());
            } else {
                inStream = mConnection.getInputStream();
            }

            if (inStream != null) {

                try {
                    Gson gson = new Gson();
                    ApiResponse response = new ApiResponse();
                    response.data = gson.fromJson(inStream, type); // What is wrong here?
                    response.responseCode = mConnection.getResponseCode();
                    response.responseMessage = mConnection.getResponseMessage();

                    return response;

                } catch (Exception e) {
                    Log.i(TAG, "Exception");
                    if (e.getMessage() != null) {
                        Log.e(TAG, e.getMessage());
                    }
                } finally {
                    inStream.close();
                }
            }

        } catch (SocketTimeoutException e) {
            Log.i(TAG, "Socket Timeout occurred");
            FileLogger.getFileLogger(mContext).ReportException(TAG + ", SocketTimeoutException ", e);
        } catch (MalformedURLException e) {
            FileLogger.getFileLogger(mContext).ReportException(TAG + ", MalformedUrlException ", e);
        } catch (IOException e) {
            Log.i(TAG," IO Exception");
            FileLogger.getFileLogger(mContext).ReportException(TAG + ", IOException ", e);

            if (e.getMessage() != null) {
                Log.i(TAG, e.getMessage());
            }

        } finally {
            mConnection.disconnect();
        }

        return null;
    }

    @Override
    protected void onPostExecute(ApiResponse response) {

        if (!isCancelled())
            mCallback.Execute(response);
    }
}

Gson類沒有fromJson(..)方法,該方法期望InputStream作為其第一個參數。 但是,它確實具有接受Reader的方法。 因此,只需將InputStream包裝在Reader實現中,確切地說就是InputStreamReader

response.data = gson.fromJson(new InputStreamReader(inStream), type);

使用類之前,請通讀javadoc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM