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

Posted

技术标签:

【中文标题】使用 GSON 从 Json 文件中恢复数据【英文标题】:Restore data from a Json file using GSON 【发布时间】:2021-06-21 14:23:26 【问题描述】:

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

【问题讨论】:

在这行代码中抛出: String content = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8) 运行调试器,它显示一个空字符串 ("")我缺少许可吗?我的清单具有读写权限。 【参考方案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();

【讨论】:

以上是关于使用 GSON 从 Json 文件中恢复数据的主要内容,如果未能解决你的问题,请参考以下文章

用GSON解析Json格式数据

Android--------使用gson解析json文件

安卓:gson 性能

Gson使用google的JsonReader读取Json文件并转化成对象

使用 gson 从 JsonArray 中获取值

从json到gson