读取对象SharedPreferences android json

时间:2013-04-03 18:28:49

标签: android json arraylist sharedpreferences

通过SharedPreferences读取对象时遇到一个小问题。 当我写一些东西它成功写入它但当我尝试检索它时,它给出了一个Json语法异常。我正在传递/检索ArrayList.My对象类正在实现Serializable。错误:

IllegalStageException需要一个String但是BEGIN_ARRAY

这是我的代码:

public static boolean saveObject(String objKey, Serializable dataObj, Context con) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
    SharedPreferences.Editor editor = prefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(dataObj);
    editor.putString(objKey, json);
    return editor.commit();
}

public static Object getObject(String objKey, Context con) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
    Gson gson = new Gson();
    String json = prefs.getString(objKey, "");
    Object o = gson.fromJson(json, objKey.getClass());
    return o;
}

我该如何做这些方法:

        if(ReadWrite.isCustomStringExistInLocal("levels", this)){
        System.out.println("Exists");
        levels = (ArrayList<Level>) ReadWrite.getObject("levels", getApplicationContext());

    }
    else{
        System.out.println("New");
        levels = new ArrayList<Level>();
        int teller =0;
        for(int i=1;i<=10;i++){
            levels.add(new Level(0, 0, teller));
            teller+=6;
        }

        ReadWrite.saveObject("levels", levels, this);

    }

0 个答案:

没有答案