R. Montanje
R. Montanje

Reputation: 63

Access JSON value called "class" with Gson

I am trying to get the value of class in the following JSON:

{    
    "battlegroup": "Misery",
    "class": 1,
    "race": 4,
    "gender": 0
}

I access the other fields (battlegroup, race etc.) with:

WoWDetails info = gson.fromJson(response, WoWDetails.class);
raceID = info.race;

WoWDetails is as following:

class WoWDetails {
// character details
   public String battlegroup;
   public Integer achievementPoints;
   public Integer race;
   public Integer class;
}

But if I try WoWDetails.class it's giving me an error saying "Unknown class: info". Which makes sense because info is not a class.

Is there a way around this? Can I escape the word "class" in any way possible?

The name class is not editable, since it's not my API.

Upvotes: 0

Views: 143

Answers (2)

PEHLAJ
PEHLAJ

Reputation: 10126

You can map the class field to JSON key using @SerializedName

WowDetails.java

public class WoWDetails {

    String battlegroup;

    @SerializedName("class")
    int className;

    int race;
    int gender;

}

Upvotes: 3

pradeep
pradeep

Reputation: 307

Set your Package name

package com.nonprofit.nonprofit;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class WoWDetails {

    @SerializedName("battlegroup")
    @Expose
    private String battlegroup;
    @SerializedName("class")
    @Expose
    private Integer _class;
    @SerializedName("race")
    @Expose
    private Integer race;
    @SerializedName("gender")
    @Expose
    private Integer gender;

    public String getBattlegroup() {
        return battlegroup;
    }

    public void setBattlegroup(String battlegroup) {
        this.battlegroup = battlegroup;
    }

    public Integer getClass_() {
        return _class;
    }

    public void setClass_(Integer _class) {
        this._class = _class;
    }

    public Integer getRace() {
        return race;
    }

    public void setRace(Integer race) {
        this.race = race;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

}

You can get your details like below

WoWDetails info = gson.fromJson(response, WoWDetails.class);

info.getGender();
info.getRace();

Upvotes: 2

Related Questions