当前位置: 首页 > 知识库问答 >
问题:

java.lang.IllegalStateException:应为BEGIN_ARRAY,但路径为BEGIN_OBJECT

伊光赫
2023-03-14

我用Gson来解析数据,但是在解析JSON对象时,我得到了和上面一样的错误,但是用JSON数组是可以的。

使用JSON对象的响应

    {
      "Code": "000",
      "Message": "Success",
      "RenewalPlans": {
        "RenewalPlan": {
          "PlanId": "123",
          "PlanName": "super plan",
          "PlanAmount": "6102"
        }
      }
    }

//json array
{
  "Code": "000",
  "Message": "Success",
  "RenewalPlans": {
    "RenewalPlan": [
      {
        "PlanId": "456",
        "PlanName": "super",
        "PlanAmount": "6102"
      },
      {
        "PlanId": "123",
        "PlanName": "Power plan",
        "PlanAmount": "123"
      }
    ]
  }
}

使用Gson解析数据

CustomerdetailsResponse customerDetailsResponse = new Gson().fromJson(new Gson().toJson(response), CustomerdetailsResponse.class);

CustomerdetailsResponse类

public class CustomerdetailsResponse implements Serializable {
    @SerializedName("Code")
    @Expose
    private String mCode;
         

    @SerializedName("Message")
    @Expose
    private String mMessage

    @SerializedName("RenewalPlans")
    @Expose
    private RenewalPlans mRenewalPlans;
   
    public String getCode() {
        return mCode;
    }

    public void setCode(String code) {
        mCode = code;
    }

  
  

    public String getMessage() {
        return mMessage;
    }

    public void setMessage(String message) {
        mMessage = message;
    }

  

  

    public RenewalPlans getRenewalPlans() {
        return mRenewalPlans;
    }

    public void setRenewalPlans(RenewalPlans renewalPlans) {
        mRenewalPlans = renewalPlans;
    }

  

 

}

RenewalPlans类

public class RenewalPlans implements Serializable {
    @SerializedName("RenewalPlan")
    @Expose

    private ArrayList<RenewalPlan> mRenewalPlan;

    public ArrayList<RenewalPlan> getRenewalPlan() {
        return mRenewalPlan;
    }

    public void setRenewalPlan(ArrayList<RenewalPlan> renewalPlan) {
        mRenewalPlan = renewalPlan;
    }

RenewalPlan类

public class RenewalPlan implements Serializable {
    @SerializedName("PlanAmount")
    @Expose

    private String mPlanAmount;
    @SerializedName("PlanId")
    @Expose

    private String mPlanId;
    @SerializedName("PlanName")
    @Expose

    private String mPlanName;

    public String getPlanAmount() {
        return mPlanAmount;
    }

    public void setPlanAmount(String planAmount) {
        mPlanAmount = planAmount;
    }

    public String getPlanId() {
        return mPlanId;
    }

    public void setPlanId(String planId) {
        mPlanId = planId;
    }

    public String getPlanName() {
        return mPlanName;
    }

    public void setPlanName(String planName) {
        mPlanName = planName;
    }

}

共有1个答案

屠锐
2023-03-14

属性mRenewalPlan的RenewalPlan类类型应为ArrayList的object instaead。 对象可以同时容纳这两者。 稍后,您可以再次将对象解析为您的需求。

 类似资料: