mrneedyourhelp
mrneedyourhelp

Reputation: 45

JSON Parsing Android Java

i would like to parse this json but im not able to do it. Heres the Json Structure:

enter image description here

For example: I would like to get String product type => Car

this Code doesnt work:

JSONObject mainData = response.getJSONObject("decode");
String productType = mainData.getString("Product Type");

Please help

Upvotes: 1

Views: 238

Answers (3)

Ashvin Sharma
Ashvin Sharma

Reputation: 583

decode is an array not an object so it should be

JSONArray mainData = response.getJSONArray("decode");

And then you can get inside objects using the index.

JSONObject jsonObj = mainData.getJSONObject(0);
String answer = jsonObj.getString("label"); //Make

Upvotes: 2

LukeWaggoner
LukeWaggoner

Reputation: 8909

If you really want to do this correctly, you'll need a custom JsonDeserializer. Like this:

public class CarDeserializer implements JsonDeserializer<Car> {
    @Override
    public Car deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

        Car car = new Gson().fromJson(json.toString(), Car.class);

        try {
            JSONObject object = new JSONObject(json.toString());

            car.setCurrency(Currency.getInstance(object.getString("price_currency")));
            car.setBalance(object.getJSONObject("balance").getInt("API Decode"));

            JSONArray decodeArray = object.getJSONArray("decode");

            for (int i = 0; i < decodeArray.length(); i++){
                JSONObject decodeObject = (JSONObject) decodeArray.get(i);

                if (decodeObject.get("label").equals("Make")){
                    car.setMake(decodeObject.getString("value"));
                } else if (decodeObject.get("label").equals("Manufacturer")){
                    car.setManufacturer(decodeObject.getString("value"));
                } else if (decodeObject.get("label").equals("Plant Country")){
                    car.setPlantCountry(decodeObject.getString("value"));
                } else if (decodeObject.get("label").equals("Product Type")){
                    car.setProductType(decodeObject.getString("value"));
                }
            }

        } catch (JSONException e){
            Log.e("CarDeserializer", e.toString(), e);
        }

        return car;
    }
}

The Car object looks like this:

public class Car {
    private int price;

    private transient Currency currency;
    private transient int balance;

    private transient String make;
    private transient String manufacturer;
    private transient String plantCountry;
    private transient String productType;

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public Currency getCurrency() {
        return currency;
    }

    public void setCurrency(Currency currency) {
        this.currency = currency;
    }

    public int getBalance() {
        return balance;
    }

    public void setBalance(int balance) {
        this.balance = balance;
    }

    public String getMake() {
        return make;
    }

    public void setMake(String make) {
        this.make = make;
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }

    public String getPlantCountry() {
        return plantCountry;
    }

    public void setPlantCountry(String plantCountry) {
        this.plantCountry = plantCountry;
    }

    public String getProductType() {
        return productType;
    }

    public void setProductType(String productType) {
        this.productType = productType;
    }
}

If Currency doesn't work for you, you can change that one to a String type like this:

@SerializedName("price_currency") private String currency;

And change the getter and setter accordingly.

If you have more objects in the decode array. You can add them as more branches in the deserializer.

This is used like this:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Car.class, new CarDeserializer());

Gson gson = gsonBuilder.create();

gson.fromJson(myJsonString, Car.class);

Note: The transient keyword in the Car class indicates to Gson that it shouldn't attempt to automatically parse the json for those fields.

Note 2: You'll need to include Gson in your project if you haven't already added it.

Upvotes: 0

Gilson Junior
Gilson Junior

Reputation: 311

You can try to use Gson

Define your class with something like that

public class YourClass implements Parcelable {

    private int price;

    @SerializedName("price_currency")
    private String priceCurrency;

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getPriceCurrency() {
        return priceCurrency;
    }

    public void setPriceCurrency(String priceCurrency) {
        this.priceCurrency = priceCurrency;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        super.writeToParcel(dest, flags);
        dest.writeInt(this.price);
        dest.writeString(this.priceCurrency);
    }

    public YourClass() {
    }

    protected YourClass(Parcel in) {
        super(in);
        this.price = in.readInt();
        this.priceCurrency = in.readString();
    }

    public static final Creator<YourClass> CREATOR = new Creator<YourClass>() {
        @Override
        public Pessoa createFromParcel(Parcel source) {
            return new YourClass(source);
        }

        @Override
        public YourClass[] newArray(int size) {
            return new YourClass[size];
        }
    };
}

and try to convert your json with something like this

Gson gson = new Gson();

YourClass yourClass = gson.fromJson(yourJson, YourClass.class);

Upvotes: 0

Related Questions