简体   繁体   中英

Proper syntax for gson with generics

I'm trying to write a reusable asynctask where I define the type of a class that Gson should deserialize to in the asynctask's constructor. Having never worked with Java Generics before, I'm a little lost on how to proceed. I can't figure out the correct syntax for the fromJson method.

The error I receive is

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

The full 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);
    }
}

The class Gson does not have a method fromJson(..) that expects an InputStream as its first argument. It does, however, have such a method that accepts a Reader . So just wrap your InputStream in a Reader implementation, InputStreamReader to be exact.

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

Go through the javadoc before you use a class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM