我正在为Android编写一个应用程序,在该应用程序中,我需要将一些对象的信息输出到文件中,以便在用户关闭该应用程序时该文件仍然存在。等等。目前,我仅将这些对象输出为字符串“ name”,每个都有自己的“价值”。仅作为序言,我对Java和Android开发非常陌生,因此对任何愚蠢的错误深表歉意。

这是输出JSON的代码:

public static String outputFile(FileOutputStream out, String name, List<String> values)
{
    String outputString = "";
    outputString += "\"meals\":[\n";

    for (int i = 0; i < values.size(); i++)
    {
        outputString += "{\"" + name + "\": \"" + values.get(i) + "\"},\n"; //output: {"name":"value"}, for every element
    }
    outputString = outputString.substring(0, outputString.length()-2); //this takes off the newline char, and the last comma.
    outputString += "\n"; //add the newline character back on.
    outputString += "]";

    Gson g = new Gson();
    String s = g.toJson(outputString);

    try
    {
        out.write(s.getBytes());
        out.close();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return outputString; //debug only
}


然后,稍后,我使用它来输入JSON并使用其各自的值解析每个对象:

public static List<String> inputFile(Context context, FileInputStream in, List<String> names)
{
    InputStreamReader inReader = new InputStreamReader(in);
    BufferedReader bufferedReader = new BufferedReader(inReader);
    StringBuilder builder = new StringBuilder();
    String line;
    String tempJson = "";

    List<String> tempList = new ArrayList<>();

    try
    {
        while ((line = bufferedReader.readLine()) != null)
        {
            builder.append(line);
            String readJson = builder.toString();
            Gson readGson = new Gson();
            tempJson = readGson.fromJson(readJson, String.class);
        }
        in.close(); //close the file here?


        JSONObject jobj = new JSONObject(tempJson);

        for (int i = 0; i < names.size(); i++)
        {
            tempList.add(jobj.getString(names.get(i))); //this should add the JSON string stored at every index i in names.
        }

        //debug:
        Toast.makeText(context, tempList.toString(), Toast.LENGTH_LONG).show();

        return tempList;
    }
    catch (Exception e)
    {
        e.printStackTrace();

        //debug:
        Toast.makeText(context, tempList.toString(), Toast.LENGTH_LONG).show();

        return new ArrayList<>(Arrays.asList("File Input Error!")); //return a blank-ish list?
    }
}
}


因此,我敢肯定有一种更简单的方法可以做到这一点。也许我没有像应该那样使用gson?任何帮助是极大的赞赏。

最佳答案

如果您只需要将列表存储到磁盘以供以后使用,这是一种非常简单的方法。

假设您有一个要存储的字符串的ArrayList:

ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("one");
arrayList.add("two");
arrayList.add("three");


您可以轻松地将它们存储在应用程序的SharedPreferences中,这些并不是真正的用户首选项,而只是键/值槽,使用持久数据可以轻松访问这些键/值槽。您不能直接存储ArrayList,但是可以存储Set,因此我们首先需要将ArrayList转换为Serializable Set:

HashSet<String> hashSet = new HashSet<>(arrayList);


然后,我们获得应用程序SharedPreferences的实例,并将新的HashSet保存到磁盘:

SharedPreferences sharedPreferences = getSharedPreferences("whatever_you_want_to_name_this", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet("name_of_the_preference_to_modify", hashSet);
editor.apply();


就是这样!准备好检索数据时,首先需要获取保存的HashSet:

SharedPreferences sharedPreferences = getSharedPreferences("whatever_you_want_to_name_this", MODE_PRIVATE);
HashSet<String> hashSet = (HashSet<String>) sharedPreferences.getStringSet("name_of_the_preference_to_modify", new HashSet<String>());


只需将其转换回ArrayList即可:

ArrayList<String> arrayList = new ArrayList<>(hashSet);


我认为这是保存列表的一种非常简单干净的方法。而且您不必弄乱所有JSON。希望能帮助到你!

07-24 09:47
查看更多