简体   繁体   English

gson与泛型的正确语法

[英]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. 我试图编写一个可重用的asynctask,在其中定义了Gson应该在asynctask的构造函数中反序列化的类的类型。 Having never worked with Java Generics before, I'm a little lost on how to proceed. 之前从未使用过Java Generics,但是我对如何进行操作有些迷茫。 I can't figure out the correct syntax for the fromJson method. 我无法为fromJson方法找出正确的语法。

The error I receive is 我收到的错误是

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

The full AsyncTask... 完整的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. Gson类没有fromJson(..)方法,该方法期望InputStream作为其第一个参数。 It does, however, have such a method that accepts a Reader . 但是,它确实具有接受Reader的方法。 So just wrap your InputStream in a Reader implementation, InputStreamReader to be exact. 因此,只需将InputStream包装在Reader实现中,确切地说就是InputStreamReader

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

Go through the javadoc before you use a class. 使用类之前,请通读javadoc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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