Question

I fecht a Json-String from my server:

{"erfolgreich":"true","id":"14"}

When I call

//result is the string above
msgServer = gson.fromJson(result, MsgSpielerErstellenSA.class);

The boolean is always false...

What am I doing wrong?

Here is my MsgSpielerErstellenSA

public class MsgSpielerErstellenSA {

    private long id;
    private boolean isErfolgreich;

    public MsgSpielerErstellenSA(long id, boolean isErfolgreich) {
        super();
        this.id = id;
        this.isErfolgreich = isErfolgreich;
    }


    public boolean isErfolgreich() {
        return isErfolgreich;
    }

    public void setErfolgreich(boolean isErfolgreich) {
        this.isErfolgreich = isErfolgreich;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }


}
Was it helpful?

Solution

Because the correct name for the boolean field is erfolgreich, not isErfolgreich. Please use the following class:

public class MsgSpielerErstellenSA {

    private long id;
    private boolean erfolgreich;

    public MsgSpielerErstellenSA(long id, boolean isErfolgreich) {
        this.id = id;
        this.erfolgreich = isErfolgreich;
    }


    public boolean isErfolgreich() {
        return erfolgreich;
    }

    public void setErfolgreich(boolean isErfolgreich) {
        this.erfolgreich = isErfolgreich;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }
}

But if you don't want to rename this field, you can use @SerializedName("erfolgreich") annotation on it

OTHER TIPS

The name of your key "erfolgreich" in json string should be same as your class data member "isErfolgreich" or you should use @SerializedName notation before define your member. if gson can not match between a class member and json keys, then use the default value for that member type. so you can use the nikis solution or you can use notation like this:

@SerializedName("erfolgreich")
private boolean isErfolgreich;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top