Gson IllegalStateException

时间:2010-11-20 03:35:40

标签: android json gson

除了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!

我的问题是......

如何让这些自定义序列化工具正常工作?就像我说的那样,我是一个菜鸟..但它看起来就像我做对了..

1 个答案:

答案 0 :(得分:0)

在它所说的文件中(在细则中有种类),静态字段被排除在外:http://sites.google.com/site/gson/gson-user-guide#TOC-Excluding-Fields-From-Serialization

您可以执行类似&#34; excludeFieldsWithModifier(Modifier.STATIC)&#34;在GSON构建器中包含它们。

相关问题