有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用GSON从Json文件还原数据

我很难读入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();
    }
}

共 (1) 个答案

  1. # 1 楼答案

    我明白了。这是不捕获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();
    }