use of com.google.gson.stream.JsonReader in project okhttp-OkGo by jeasonlzy.
the class JsonConvert method convertSuccess.
/**
* 该方法是子线程处理,不能做ui相关的工作
* 主要作用是解析网络返回的 response 对象,生产onSuccess回调中需要的数据对象
* 这里的解析工作不同的业务逻辑基本都不一样,所以需要自己实现,以下给出的时模板代码,实际使用根据需要修改
* <pre>
* OkGo.get(Urls.URL_METHOD)//
* .tag(this)//
* .execute(new DialogCallback<LzyResponse<ServerModel>>(this) {
* @Override
* public void onSuccess(LzyResponse<ServerModel> responseData, Call call, Response response) {
* handleResponse(responseData.data, call, response);
* }
* });
* </pre>
*/
@Override
public T convertSuccess(Response response) throws Exception {
// 重要的事情说三遍,不同的业务,这里的代码逻辑都不一样,如果你不修改,那么基本不可用
// 重要的事情说三遍,不同的业务,这里的代码逻辑都不一样,如果你不修改,那么基本不可用
// 重要的事情说三遍,不同的业务,这里的代码逻辑都不一样,如果你不修改,那么基本不可用
//以下代码是通过泛型解析实际参数,泛型必须传
//这里为了方便理解,假如请求的代码按照上述注释文档中的请求来写,那么下面分别得到是
//com.lzy.demo.callback.DialogCallback<com.lzy.demo.model.LzyResponse<com.lzy.demo.model.ServerModel>> 得到类的泛型,包括了泛型参数
Type genType = getClass().getGenericSuperclass();
//从上述的类中取出真实的泛型参数,有些类可能有多个泛型,所以是数值
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
//我们的示例代码中,只有一个泛型,所以取出第一个,得到如下结果
//com.lzy.demo.model.LzyResponse<com.lzy.demo.model.ServerModel>
Type type = params[0];
// https://github.com/jeasonlzy/okhttp-OkGo/blob/master/README_JSONCALLBACK.md 这里的第一种方式定义就可以实现
if (!(type instanceof ParameterizedType))
throw new IllegalStateException("没有填写泛型参数");
//如果确实还有泛型,那么我们需要取出真实的泛型,得到如下结果
//class com.lzy.demo.model.LzyResponse
//此时,rawType的类型实际上是 class,但 Class 实现了 Type 接口,所以我们用 Type 接收没有问题
Type rawType = ((ParameterizedType) type).getRawType();
//这里获取最终内部泛型的类型 com.lzy.demo.model.ServerModel
Type typeArgument = ((ParameterizedType) type).getActualTypeArguments()[0];
//这里我们既然都已经拿到了泛型的真实类型,即对应的 class ,那么当然可以开始解析数据了,我们采用 Gson 解析
//以下代码是根据泛型解析数据,返回对象,返回的对象自动以参数的形式传递到 onSuccess 中,可以直接使用
JsonReader jsonReader = new JsonReader(response.body().charStream());
if (typeArgument == Void.class) {
//无数据类型,表示没有data数据的情况(以 new DialogCallback<LzyResponse<Void>>(this) 以这种形式传递的泛型)
SimpleResponse simpleResponse = Convert.fromJson(jsonReader, SimpleResponse.class);
response.close();
//noinspection unchecked
return (T) simpleResponse.toLzyResponse();
} else if (rawType == LzyResponse.class) {
//有数据类型,表示有data
LzyResponse lzyResponse = Convert.fromJson(jsonReader, type);
response.close();
int code = lzyResponse.code;
//一般来说服务器会和客户端约定一个数表示成功,其余的表示失败,这里根据实际情况修改
if (code == 0) {
//noinspection unchecked
return (T) lzyResponse;
} else if (code == 104) {
//比如:用户授权信息无效,在此实现相应的逻辑,弹出对话或者跳转到其他页面等,该抛出错误,会在onError中回调。
throw new IllegalStateException("用户授权信息无效");
} else if (code == 105) {
//比如:用户收取信息已过期,在此实现相应的逻辑,弹出对话或者跳转到其他页面等,该抛出错误,会在onError中回调。
throw new IllegalStateException("用户收取信息已过期");
} else if (code == 106) {
//比如:用户账户被禁用,在此实现相应的逻辑,弹出对话或者跳转到其他页面等,该抛出错误,会在onError中回调。
throw new IllegalStateException("用户账户被禁用");
} else if (code == 300) {
//比如:其他乱七八糟的等,在此实现相应的逻辑,弹出对话或者跳转到其他页面等,该抛出错误,会在onError中回调。
throw new IllegalStateException("其他乱七八糟的等");
} else {
throw new IllegalStateException("错误代码:" + code + ",错误信息:" + lzyResponse.msg);
}
} else {
response.close();
throw new IllegalStateException("基类错误无法解析!");
}
}
use of com.google.gson.stream.JsonReader in project plaid by nickbutcher.
the class DenvelopingConverter method responseBodyConverter.
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
// This converter requires an annotation providing the name of the payload in the envelope;
// if one is not supplied then return null to continue down the converter chain.
final String payloadName = getPayloadName(annotations);
if (payloadName == null)
return null;
final TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
return new Converter<ResponseBody, Object>() {
@Override
public Object convert(ResponseBody body) throws IOException {
try (JsonReader jsonReader = gson.newJsonReader(body.charStream())) {
jsonReader.beginObject();
while (jsonReader.hasNext()) {
if (payloadName.equals(jsonReader.nextName())) {
return adapter.read(jsonReader);
} else {
jsonReader.skipValue();
}
}
return null;
} finally {
body.close();
}
}
};
}
use of com.google.gson.stream.JsonReader in project Anki-Android by Ramblurr.
the class DeckTask method doInBackgroundImportReplace.
private TaskData doInBackgroundImportReplace(TaskData... params) {
Log.i(AnkiDroidApp.TAG, "doInBackgroundImportReplace");
Collection col = params[0].getCollection();
String path = params[0].getString();
Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources();
// extract the deck from the zip file
String fileDir = AnkiDroidApp.getCurrentAnkiDroidDirectory() + "/tmpzip";
File dir = new File(fileDir);
if (dir.exists()) {
BackupManager.removeDir(dir);
}
publishProgress(new TaskData(res.getString(R.string.import_unpacking)));
// from anki2.py
String colFile = fileDir + "/collection.anki2";
ZipFile zip;
try {
zip = new ZipFile(new File(path), ZipFile.OPEN_READ);
} catch (IOException e) {
Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - Error while unzipping: ", e);
AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace0");
return new TaskData(false);
}
if (!Utils.unzipFiles(zip, fileDir, new String[] { "collection.anki2", "media" }, null) || !(new File(colFile)).exists()) {
return new TaskData(-2, null, false);
}
Collection tmpCol = null;
try {
tmpCol = Storage.Collection(colFile);
if (!tmpCol.validCollection()) {
tmpCol.close();
return new TaskData(-2, null, false);
}
} finally {
if (tmpCol != null) {
tmpCol.close();
}
}
publishProgress(new TaskData(res.getString(R.string.importing_collection)));
String colPath;
if (col != null) {
// unload collection and trigger a backup
colPath = col.getPath();
AnkiDroidApp.closeCollection(true);
BackupManager.performBackup(colPath, true);
}
// overwrite collection
colPath = AnkiDroidApp.getCollectionPath();
File f = new File(colFile);
f.renameTo(new File(colPath));
int addedCount = -1;
try {
col = AnkiDroidApp.openCollection(colPath);
// because users don't have a backup of media, it's safer to import new
// data and rely on them running a media db check to get rid of any
// unwanted media. in the future we might also want to duplicate this step
// import media
HashMap<String, String> nameToNum = new HashMap<String, String>();
HashMap<String, String> numToName = new HashMap<String, String>();
File mediaMapFile = new File(fileDir, "media");
if (mediaMapFile.exists()) {
JsonReader jr = new JsonReader(new FileReader(mediaMapFile));
jr.beginObject();
String name;
String num;
while (jr.hasNext()) {
num = jr.nextName();
name = jr.nextString();
nameToNum.put(name, num);
numToName.put(num, name);
}
jr.endObject();
jr.close();
}
String mediaDir = col.getMedia().getDir();
int total = nameToNum.size();
int i = 0;
for (Map.Entry<String, String> entry : nameToNum.entrySet()) {
String file = entry.getKey();
String c = entry.getValue();
File of = new File(mediaDir, file);
if (!of.exists()) {
Utils.unzipFiles(zip, mediaDir, new String[] { c }, numToName);
}
++i;
publishProgress(new TaskData(res.getString(R.string.import_media_count, (i + 1) * 100 / total)));
}
zip.close();
// delete tmp dir
BackupManager.removeDir(dir);
publishProgress(new TaskData(res.getString(R.string.import_update_counts)));
// Update the counts
DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col));
if (result == null) {
return null;
}
return new TaskData(addedCount, result.getObjArray(), true);
} catch (RuntimeException e) {
Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - RuntimeException: ", e);
AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace1");
return new TaskData(false);
} catch (FileNotFoundException e) {
Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - FileNotFoundException: ", e);
AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace2");
return new TaskData(false);
} catch (IOException e) {
Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - IOException: ", e);
AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace3");
return new TaskData(false);
}
}
use of com.google.gson.stream.JsonReader in project Anki-Android by Ramblurr.
the class Anki2Importer method run.
public int run() {
publishProgress(false, 0, 0, false);
try {
// extract the deck from the zip file
String tempDir = AnkiDroidApp.getCurrentAnkiDroidDirectory() + "/tmpzip";
// from anki2.py
String colFile = tempDir + "/collection.anki2";
if (!Utils.unzipFiles(mZip, tempDir, new String[] { "collection.anki2", "media" }, null) || !(new File(colFile)).exists() || !Storage.Collection(colFile).validCollection()) {
return -2;
}
// we need the media dict in advance, and we'll need a map of fname number to use during the import
File mediaMapFile = new File(tempDir, "media");
HashMap<String, String> numToName = new HashMap<String, String>();
if (mediaMapFile.exists()) {
JsonReader jr = new JsonReader(new FileReader(mediaMapFile));
jr.beginObject();
String name;
String num;
while (jr.hasNext()) {
num = jr.nextName();
name = jr.nextString();
nameToNum.put(name, num);
numToName.put(num, name);
}
jr.endObject();
jr.close();
}
_prepareFiles(colFile);
publishProgress(true, 0, 0, false);
int cnt = -1;
try {
cnt = _import();
} finally {
// do not close collection but close only db (in order not to confuse access counting in storage.java
// Note that the media database is still open and needs to be closed below.
AnkiDatabaseManager.closeDatabase(mSrc.getPath());
}
// import static media
String mediaDir = mCol.getMedia().getDir();
if (nameToNum.size() != 0) {
for (Map.Entry<String, String> entry : nameToNum.entrySet()) {
String file = entry.getKey();
String c = entry.getValue();
if (!file.startsWith("_") && !file.startsWith("latex-")) {
continue;
}
File of = new File(mediaDir, file);
if (!of.exists()) {
Utils.unzipFiles(mZip, mediaDir, new String[] { c }, numToName);
}
}
}
mZip.close();
mSrc.getMedia().close();
// delete tmp dir
File dir = new File(tempDir);
BackupManager.removeDir(dir);
publishProgress(true, 100, 100, true);
return cnt;
} catch (RuntimeException e) {
Log.e(AnkiDroidApp.TAG, "RuntimeException while importing ", e);
return -1;
} catch (IOException e) {
Log.e(AnkiDroidApp.TAG, "IOException while importing ", e);
return -1;
}
}
use of com.google.gson.stream.JsonReader in project SeriesGuide by UweTrottmann.
the class JsonImportTask method importFromJson.
private void importFromJson(@JsonExportTask.BackupType int type, FileInputStream in) throws JsonParseException, IOException, IllegalArgumentException {
Gson gson = new Gson();
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
reader.beginArray();
if (type == JsonExportTask.BACKUP_SHOWS) {
while (reader.hasNext()) {
Show show = gson.fromJson(reader, Show.class);
addShowToDatabase(show);
}
} else if (type == JsonExportTask.BACKUP_LISTS) {
while (reader.hasNext()) {
List list = gson.fromJson(reader, List.class);
addListToDatabase(list);
}
} else if (type == JsonExportTask.BACKUP_MOVIES) {
while (reader.hasNext()) {
Movie movie = gson.fromJson(reader, Movie.class);
addMovieToDatabase(movie);
}
}
reader.endArray();
reader.close();
}
Aggregations