簡體   English   中英

使用 GSON 從 Json 文件恢復數據

[英]Restore data from a Json file using GSON

我很難讀取 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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM