gpt4 book ai didi

java - 具有泛型的 gson 的正确语法

转载 作者:行者123 更新时间:2023-11-29 21:14:43 26 4
gpt4 key购买 nike

我正在尝试编写一个可重用的异步任务,我在其中定义了 Gson 应该在异步任务的构造函数中反序列化的类的类型。以前从未使用过 Java 泛型,我对如何进行有点迷茫。我想不出 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在使用类(class)之前。

关于java - 具有泛型的 gson 的正确语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21747363/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com