11684
11684

Reputation: 7517

Incompatible types when using GSON

First: this is my first time using GSON.

Trying to parse some JSON, I got "incompatible types"...

Gson gson = new Gson();
PlayerData data = gson.fromJson(response, PlayerData.class); // Incompatible types...

PlayerData is an inner class:

class PlayerData {
    public Point position;
    public String mapname;
    public int level;

    public PlayerData() {}
}

What causes it? In the GSON docs there is clearly a method public <T> T fromJson(String json, Class<T> classOfT) throws JsonSyntaxException and I am doing at (AFAIK) just like Google in it's GSON User Guide.

Edit:
XCode was doing something strange, when I tried to compile this with Terminal everything worked, except for my request to the server, what resulted in a couple of NPE's, because response remained empty. Thanks to maaartinus I learned that there shouldn't be an compiler error so I tried to compile it without XCode.

Upvotes: 0

Views: 975

Answers (2)

maaartinus
maaartinus

Reputation: 46482

For me it compiles, but I had to replace GSON by Gson. Either you were sloppy when writing this question or you're using some "GSON" I've never heard about.

Is your response a String???

Once you get it running, you'll need the answer by Vrushank Desai.

Upvotes: 1

Vrushank
Vrushank

Reputation: 2813

Try making your inner class static or you'll need a custom InstanceCreator for it as stated in the Gson User Guide

Gson can not automatically deserialize the pure inner classes since their no-args constructor also need a reference to the containing Object which is not available at the time of deserialization. You can address this problem by either making the inner class static or by providing a custom InstanceCreator for it.

Upvotes: 3

Related Questions