Retrofit get JsonSyntaxException Error

时间:2017-06-17 07:56:58

标签: android retrofit2

当我尝试从webService获取此结果时:

{
    "bankInfo":
    [
        {
            "id": "2",
            "title": "BANK A",
            "alias": "A"
        },
        {
            "id": "3",
            "title": "BANK B",
            "alias": "B"
        },
        {
            "id": "4",
            "title": "BANK C",
            "alias": "C"
        }
    ]
}

使用此代码:

ActiveBanks activeBanks = new ActiveBanks();

Call<ActiveBanks> call = behandamService.activeBanksCall(activeBanks);
call.enqueue(new Callback<ActiveBanks>() {
    @Override
    public void onResponse(Call<ActiveBanks> call, final Response<ActiveBanks> response) {
        if (response.isSuccessful()) {

        }
    }
    @Override
    public void onFailure(Call<ActiveBanks> call, Throwable t) {
        t.printStackTrace();
        if (t.getMessage() != null) Log.e("ActiveBanks: ", t.getMessage());
    }
});

ActiveBanks结构:

public class ActiveBanks {
    private JSONArray bankInfo;

    public ActiveBanks() {
    }

    public JSONArray getBankInfo() {
        return bankInfo;
    }

    public void setBankInfo(JSONArray bankInfo) {
        this.bankInfo = bankInfo;
    }
}

我收到此错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 14 path $.bankInfo

1 个答案:

答案 0 :(得分:1)

你必须将模型类命名为:

public class BankInfo {

@SerializedName("id")
@Expose
private String id;
@SerializedName("title")
@Expose
private String title;
@SerializedName("alias")
@Expose
private String alias;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getAlias() {
return alias;
}

public void setAlias(String alias) {
this.alias = alias;
}

}

主要模型类:

public class ActiveBanks{

@SerializedName("bankInfo")
@Expose
private List<BankInfo> bankInfo = null;

public List<BankInfo> getBankInfo() {
return bankInfo;
}

public void setBankInfo(List<BankInfo> bankInfo) {
this.bankInfo = bankInfo;
}

}