我是一個noob,當涉及到基本上所有除了SharedPreferences和一些SQLite的存儲形式。我做了一些搜索,發現JSON + GSON是將對象及其字段解析爲可存儲的字符串的快速方法。Gson IllegalStateException
所以,在我的遊戲,我有一個Player
對象,有也是我自己的類字段:
public class Player {
private int something_game_related = 1;
private Skill equipped_skill;
private Item equipped_weapon;
public Player() {}
}
我懷疑這些類的問題,因爲當我嘗試運行一個簡單的保存方法:
private class ItemSerializer implements JsonSerializer<Item> {
public JsonElement serialize(Item src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.toString());
}
}
private class SkillSerializer implements JsonSerializer<Skill> {
public JsonElement serialize(Skill src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.toString());
}
}
public void doSave() {
GsonBuilder gson = new GsonBuilder();
//Both custom classes have zero-arg constructors so we don't need to register those
gson.registerTypeAdapter(Item.class, new ItemSerializer());
gson.registerTypeAdapter(Skill.class, new SkillSerializer());
Gson g = gson.create();
String mPlayer = "";
Type player = new TypeToken<Player>(){}.getType();
try{
mPlayer = g.toJson(GameView.mPlayer, player);
}
catch (Exception e) {e.printStackTrace();}
}
我得到這個異常:java.lang.IllegalStateException: How can the type variable not be present in the class declaration!
我的問題是..
如何讓這些自定義序列化器工作?就像我說的,我是小白..但它看起來像我這樣做是正確的..
我剛剛發現如果我嘗試運行'try {mPlayer = g.toJson(new Player())}'它工作正常!我認爲它與我通過的「靜態」對象有關。靜態對象是否允許? – Snailer 2010-11-20 23:34:41