使用GSON从Json文件中恢复数据



我很难读取Json文件。我的restoreObjects ArrayList始终为null。此外,我甚至不确定是否应该这样解析文件路径,但我似乎不明白应该如何使用ContentResolver。任何见解都将不胜感激。

public void restoreObjects(Uri backupJsonFile) {
File backupFilePath = new File(backupJsonFile.getPath());
String sFile = backupFilePath.toString();
String split[] = sFile.split(":");
String filePath = Environment.getExternalStorageDirectory() + "/" + split[1];
//Get all the current "Objects" that are saved.
ArrayList<Object> currentObjects = getAllObjects();
int newid = getNewObjectId();
try {
//get contents of Json file 
JsonReader backupData = new JsonReader(new FileReader(filePath));
//This is were the array should be populated, but is left null
ArrayList<Object> restoreObjects = gsonBuilder.fromJson(backupData, type);
for (Object rObject : restoreObjects) {
if (currentObject.contains(rObject.getId())) {
//Do work here
}
}
} catch (JsonSyntaxException | NullPointerException | IOException e) {
e.printStackTrace();
Toast.makeText(mContext, R.string.error, Toast.LENGTH_SHORT).show();
}
}

想明白了。这是未捕获InputStream和未使用getContentResolver定位文件的组合。

public void restoreObjects(Uri backupFile) {
ArrayList<Object> currentObjects = getAllObjects();

try {
InputStream is = mContext.getContentResolver().openInputStream(backupFile);
String jsonString;
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
jsonString = new String(buffer, "UTF-8");

ArrayList<Object> restoreObjects = gsonBuilder.fromJson(jsonString, type);
for (Objects rObject : restoreObjects) {
if (currentObjects.contains(rObject.getId())) {
//do work
}
}
}
} catch (JsonSyntaxException | NullPointerException | IOException e) {
e.printStackTrace();
Toast.makeText(mContext, R.string.error, Toast.LENGTH_SHORT).show();
}
Toast.makeText(mContext, "R.string.success", Toast.LENGTH_SHORT).show();
}

最新更新