1

我在通过 SharedPreferences 读取对象时遇到了一个小问题。当我写东西时,它成功地写了它,但是当我尝试检索它时,它给出了一个 Json 语法异常。我正在传递/检索一个 ArrayList。我的对象类正在实现 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);

    }
4

0 回答 0