Stuck on getting JSONArray from a JSONObject

212 views Asked by At

I have a JSON response that looks something like:

And a Subscription POJO class and inside it, is an Arraylist of the "subscriptionPlans":

SubscriptionDetails.java

@Expose()
@SerializedName("subscriptionPlans")
public ArrayList<SubscriptionPlans> subscriptionPlans;


public ArrayList<SubscriptionPlans> getSubscriptionPlans() {
    return subscriptionPlans;
}

@Override
public String toString() {
    return "SubscriptionDetails{" +
            "subscriptionPlans=" + subscriptionPlans +
            '}';
}

SubscriptionPlans.java

@SerializedName("plan_name")
@Expose
public String planName;

@SerializedName("description")
@Expose
public String description;

@SerializedName("amount")
@Expose
public String amount;

public String getPlanName() {
    return planName;
}

public String getDescription() {
    return description;
}

public String getAmount() {
    return amount;
}

I'm using Gson to get the data from the JSON and populate it to the various POJO classes like so:

Gson gson = new Gson();
SubscriptionDetails subscriptionDetails = gson.fromJson(String.valueOf(jsonObject.getJSONArray("subscriptionPlans")), SubscriptionDetails.class);
ArrayList<SubscriptionPlans> subscriptionPlans = subscriptionDetails.getSubscriptionPlans();

String amount = subscriptionPlans.get(0).getAmount();

however, I get the error response, java.lang.IllegalStateException:Expected BEGIN_OBJECT but was BEGIN_ARRAY at line column 2 path $

What I'm I missing or not doing correct here?

1

There are 1 answers

0
user3118604 On BEST ANSWER

pass to GSON the entire string, not just String.valueOf(jsonObject.getJSONArray("subscriptionPlans")):

SubscriptionDetails subscriptionDetails = gson.fromJson(String.valueOf(jsonObject), SubscriptionDetails.class);