使用GSON从Json文件恢复数据

kq0g1dla  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(277)

我很难读取Json文件。我的restoreObjects ArrayList总是空的。而且,我甚至不确定我是否应该像那样解析文件路径,但我似乎不明白我应该如何使用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();
    }
}
slsn1g29

slsn1g291#

解决了。这是没有捕获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();
}

相关问题