GSON预计BEGIN_OBJECT但是BEGIN_ARRAY

时间:2014-11-26 10:20:01

标签: android json gson

我有下面的JSON和Model类,如何使用GSOn反序列化这个JSON我得到一个例外,如“预期的BEGIN_OBJECT但是BEGIN_ARRAY”,下面的snippet.how形成了以下JSON数据的模型calss

Gson gson = new Gson();
Referrals referrals = gson.fromJson(response.toString(),Referrals.class);

public class Referrals {

private List<Referral> referrals;

}

public class Referral implements Serializable{

private String referral_id;
private String notes;
private String attachment;
private String patient_consent;
private String date_of_referral;
private String is_read;
private String type;
 }

{
  "referrals": [
    {
      "referral_id": "2",
      "notes": "test issue",
      "attachment": "test.jpg",
      "patient_consent": "Yes",
      "date_of_referral": "2014-11-26 15:14:45",
      "is_read": "0",
      "type": "sender"
    },
    {
      "referral_id": "1",
      "notes": "ok",
      "attachment": null,
      "patient_consent": "Yes",
      "date_of_referral": "2014-11-26 11:52:43",
      "is_read": "0",
      "type": "sender"
    }
  ],
  "response": "1"
}

3 个答案:

答案 0 :(得分:0)

尝试更改此

private List<Referral> referrals;

private ArrayList<Referral> referrals;

同时制作Referrals课程Serializable

答案 1 :(得分:0)

试试这个..希望这会奏效。

private Referral[] referrals;

答案 2 :(得分:0)

创建一个名为ReferralHandler的类:

public class ReferralHandler implements Serializable {

@SerializedName("referrals")
private ArrayList<Referral> referrals = new ArrayList<Referral>();

public ArrayList<Referral> getReferrals() {
    return referrals;
}

然后创建一个名为Referral的类:

public class Referral implements Serializable {

@SerializedName("referral_id")
private String referral_id;
@SerializedName("notes")
private String notes;
@SerializedName("attachment")
private String attachment;
@SerializedName("patient_consent")
private String patient_consent;
@SerializedName("date_of_referral")
private String date_of_referral;
@SerializedName("is_read")
private String is_read;
@SerializedName("type")
private String type;

// setters and getters
}

最后解析,你必须写:

ReferralHandler referralsObject = gson.fromJson(response.toString(), ReferralHandler.class);
ArrayList<Referral> referrals = referralsObject.getReferrals();