开发者

Gson IllegalStateException

I'm a noob when it comes to basically all forms of storage aside from SharedPreferences and some SQLite. I did some searching and found that JSON+GSON was a fast way to parse Objects and their fields into storable Strings.

So, in my game, I have a Player object which has fields that are also my own classes:

public class Player {
    private int something_game_related = 1;
    private Skill equipped_skill;
    private Item equipped_weapon;

    public Player () {}
}

I suspect those classes are the problem, because when I try to run a simple save method:

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 SkillSeria开发者_Python百科lizer() );
    Gson g = gson.create();
    String mPlayer = "";
    Type player = new TypeToken<Player>(){}.getType();
    try{
        mPlayer = g.toJson( GameView.mPlayer, player );   
    }
 catch (Exception e) {e.printStackTrace();}
 }

I get this Exception: java.lang.IllegalStateException: How can the type variable not be present in the class declaration!

My Question is..

How do I get these custom serializers to work? Like I said, I'm a noob.. but it looks like I did it right..


In the docs it says (kind of in the fine print) that static fields are excluded: http://sites.google.com/site/gson/gson-user-guide#TOC-Excluding-Fields-From-Serialization

You can do something like "excludeFieldsWithModifier(Modifier.STATIC)" in the GSON builder to include them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜