猿问

反序列化自定义对象的序列化 ArrayList,添加对象,然后重新序列化

我正在尝试为我正在使用 android studios 制作的应用程序存储对象的自定义数组列表。每当用户按下按钮时,我都需要能够将新对象添加到列表中。我的方法是首先使用正确的类型(try/catch 的捕获)初始化数组列表的空序列化版本。然后将该数组反序列化为名为“RecoTrackGameCollection”的临时数组列表,然后添加新对象,并重新序列化数组并保存它。


我遇到的问题是,当我尝试将任何对象添加到“RecoTrackGameCollection”时,代码会失败并运行捕获。


感谢您花时间看这个。如果您需要更多信息,请告诉我。


try {

    //get shared pref

    SharedPreferences prefs = mContext.getSharedPreferences("SavedGames", Context.MODE_PRIVATE);

    //deserilize

    Gson gson = new Gson();

    String serialRecoverList = prefs.getString("SavedGames", "");

    Log.wtf("String Recover", serialRecoverList);

    Type type = new TypeToken<List<Game>>(){}.getType();

    ArrayList<Game> RecoTrackGameCollection = gson.fromJson(serialRecoverList, type);


    //add game

    RecoTrackGameCollection.add(SearchGameCollection.get(position));


    //reserilize

    Gson NewGson = new Gson();

    String JsonTrakingGames = NewGson.toJson(RecoTrackGameCollection);

    SharedPreferences.Editor editor = prefs.edit();


    editor.putString("Games", JsonTrakingGames);

    editor.commit();



    Toast.makeText(mContext , "Game Saved", Toast.LENGTH_LONG).show();


} catch (Exception e) {


    Gson gson = new Gson();

    String JsonTrakingGames = gson.toJson(TrackGameCollection);

    SharedPreferences prefs = mContext.getSharedPreferences("SavedGames", Context.MODE_PRIVATE);

    SharedPreferences.Editor editor = prefs.edit();


    editor.putString("Games", JsonTrakingGames);


    editor.commit();


    Toast.makeText(mContext , "iniatlizing", Toast.LENGTH_LONG).show();


}

这是游戏类


public class Game {

    String name;

    double price;

    String link;

    //constructor

    Game(String name, double price,String link){

        this.name = name;

        this.price = price;

        this.link = link;


    }


}

我相信我的错误在于阵列的反序列化。特别是这一行:


ArrayList<Game> RecoTrackGameCollection = gson.fromJson(serialRecoverList, 

type);


慕容森
浏览 146回答 1
1回答

一只斗牛犬

那是因为您在保存和获取列表时使用了不同的密钥。您可以使用以下方法保存列表:private void saveGames(Lis<Game> games) {&nbsp; &nbsp;Gson gson = new Gson();&nbsp; &nbsp;String json = gson.toJson(games);&nbsp; &nbsp;SharedPreferences prefs = ctx.getSharedPreferences("SavedGames", Context.MODE_PRIVATE);&nbsp; &nbsp;SharedPreferences.Editor editor = prefs.edit();&nbsp; &nbsp;editor.putString("Games", json);&nbsp; &nbsp;editor.commit();}以及以下获取列表:private List<Game> getGames(Context ctx) {&nbsp; Gson gson = new Gson();&nbsp; SharedPreferences prefs = ctx.getSharedPreferences("SavedGames", Context.MODE_PRIVATE);&nbsp; String json = prefs.getString("Games", "");&nbsp; if(json.isEmpty()) {&nbsp; &nbsp; return new ArrayList<>();&nbsp; } else {&nbsp; &nbsp; Type type = new TypeToken<List<Game>>(){}.getType();&nbsp; &nbsp; return gson.fromJson(json, type);&nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答