适用于泛型的gson的正确语法

时间:2014-02-13 07:02:42

标签: java android generics android-asynctask gson

我正在尝试编写一个可重用的asynctask,我在asynctask的构造函数中定义了Gson应该反序列化的类的类型。之前从未使用过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);
    }
}

1 个答案:

答案 0 :(得分:2)

Gson没有方法fromJson(..),希望InputStream作为其第一个参数。但是,它确实有一种接受Reader的方法。因此,只需将InputStream包含在Reader实施中,InputStreamReader即可。

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

在使用课程之前,请先浏览javadoc