0

除了 SharedPreferences 和一些 SQLite 之外,基本上所有形式的存储我都是菜鸟。我做了一些搜索,发现 JSON+GSON 是一种将对象及其字段解析为可存储字符串的快速方法。

所以,在我的游戏中,我有一个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!

我的问题是..

如何让这些自定义序列化程序工作?就像我说的,我是菜鸟.. 但看起来我做对了..

4

1 回答 1

0

在文档中它说(在细则中)排除了静态字段:http ://sites.google.com/site/gson/gson-user-guide#TOC-Excluding-Fields-From-Serialization

您可以在 GSON 构建器中执行类似“excludeFieldsWithModifier(Modifier.STATIC)”的操作来包含它们。

于 2011-02-11T09:55:30.087 回答