保存和检索Java / Android中的自定义对象列表

时间:2014-09-21 05:10:02

标签: android generics storage

我是Generics世界的新手,我正在尝试编写一个实用程序类,它将获取一个对象列表并将其保存到商店然后将其检索回来。

这是我为保存列表所写的内容:

    public static void saveListToStore(Context ctx, String fileName, list<Object> listToStore) throws IOException
    {
       String elemValue = "";
       Gson gson = new Gson();

       try {
          FileOutputStream fileOutputStream = ctx.openFileOutput(fileName, ctx.MODE_PRIVATE);

          elemValue= gson.toJson(listToStore);
          fileOutputStream.write(elemValue.getBytes());
          objectOutputStream.close();

       } catch (FileNotFoundException e) {
          e.printStackTrace();
       }
     }

但是当我尝试检索时,我不会知道列表中存在的对象类型,也无法重建它。我不想把类型比较,因为我想保存任何类型的自定义类,列表可能是巨大的。

我想从内容本身推断出类型。我在考虑将类型保存为第一行,然后是数据。因此,在检索时,我可以先获取类型,然后对对象进行类型转换。但有没有其他更清洁的方法来实现这一目标?

2 个答案:

答案 0 :(得分:1)

Ur Object应该实现Serializable,下面的代码可以帮助您进行读写

public static void readListToStore(Context ctx, String fileName, List<Object> listToStore) throws IOException {
    SharedPreferences storeDataPref = ctx.getSharedPreferences("UR_KEY", Context.MODE_PRIVATE);
    String elemValue = storeDataPref.getString("UR_NAME", null);
    if (elemValue != null) {
        Type listType = new TypeToken<ArrayList<Object>>() {
        }.getType();
        listToStore = new Gson().fromJson(elemValue, listType);
    }
}

public static void saveListToStore(Context ctx, String fileName, List<Object> listToStore) throws IOException {
    String elemValue = "";
    Gson gson = new Gson();
    try {
        FileOutputStream fileOutputStream = ctx.openFileOutput(fileName, ctx.MODE_PRIVATE);
        elemValue = gson.toJson(listToStore);
        SharedPreferences storeDataPref = ctx.getSharedPreferences("UR_KEY", Context.MODE_PRIVATE);
        Editor storeDataEditor = storeDataPref.edit();
        storeDataEditor.clear();
        storeDataEditor.putString("UR_NAME", elemValue).apply();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

答案 1 :(得分:0)

取自这个问题:Trouble with Gson serializing an ArrayList of POJO's

“您需要提供有关您正在使用的List的特定泛型类型(或您使用的任何泛型类型)的Gson信息。特别是在反序列化JSON时,它需要该信息才能确定对象的类型它应该将每个数组元素反序列化为。

Type listOfTestObject = new TypeToken<List<TestObject>>(){}.getType();
String s = gson.toJson(list, listOfTestObject);
List<TestObject> list2 = gson.fromJson(s, listOfTestObject);

这已在Gson user guide中记录。

您可以将字符串写入并读取到文件中。 List可以是实现List接口的任何集合类型

相关问题