我有一个类似于JSON的响应:

java - 坚持从JSONObject获取JSONArray-LMLPHP

Subscription POJO类及其内部是“ 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;
}


我正在使用Gson从JSON获取数据并将其填充到各种POJO类中,如下所示:

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();


但是,我得到了错误响应,
java.lang.IllegalStateException:Expected BEGIN_OBJECT but was BEGIN_ARRAY at line column 2 path $

我在这里缺少什么或做错了什么?

最佳答案

将整个字符串传递给GSON,而不仅仅是String.valueOf(jsonObject.getJSONArray("subscriptionPlans"))

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

09-27 10:37