改造处理空Jsonarray

时间:2018-02-27 10:42:52

标签: android gson retrofit

我有这样的改造:

public static Retrofit getClient(MCrypt mCrypt) throws Exception {
    if (retrofit == null) {
        OkHttpClient okHttpClient;


        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            okHttpClient = new OkHttpClient.Builder()
                    .readTimeout(90000, TimeUnit.MILLISECONDS)
                    .connectTimeout(90000, TimeUnit.MILLISECONDS)
                    .addInterceptor(interceptor)
                    .build();
        } else {
            okHttpClient = new OkHttpClient.Builder()
                    .readTimeout(90000, TimeUnit.MILLISECONDS)
                    .connectTimeout(90000, TimeUnit.MILLISECONDS)
                    .build();
        }


        Gson gson = new GsonBuilder().setPrettyPrinting()
                .registerTypeAdapter(FeedbackDetails.class,
                        new FeedbackDetailsDeserializer())
                .create();

        retrofit = new Retrofit.Builder()
                .baseUrl(mCrypt.decrypt(host_name))
                .addConverterFactory(GsonConverterFactory.create(gson))
                // TODO: 14-02-2018 change httpclient to previous
                .client(okHttpClient)
                .build();
    }
    return retrofit;
}

public static class FeedbackDetailsDeserializer
        implements JsonDeserializer<FeedbackDetails> {

    private Gson gson = new GsonBuilder().setPrettyPrinting().create();

    @Override
    public FeedbackDetails deserialize(JsonElement json, Type typeOfT,
                                       JsonDeserializationContext context)
            throws JsonParseException {

        if (json.isJsonArray()) return null;
        return gson.fromJson(json, typeOfT);
    }

}

这就是我使用Gson

解析数据的方法
private void parseResponse(String data) {

    try {
        JSONArray jsonArray = new JSONArray(sendbackActivity.mCrypt.decrypt(data));

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            MainLeadData mainLeadData = new Gson().fromJson(object.toString(), MainLeadData.class);
            sendbackActivity.leadDataArrayList.add(mainLeadData);
        }
        Utility.printMessage("lead arraylist size ..." + sendbackActivity.leadDataArrayList.size());

        setAdapter();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

有数据时的实际响应:

  "feedback_details":{
"id":"79",
"lead_id":"86075",
"account_id":"1543",
"document_id":"582346",
"reason_id":"2",
"description":"Aadhar Card ",
"sales_remark":null,
"lat":"",
"long":"",
"status":"2",
"created_at":"2018-02-27 12:29:59",
"updated_at":"2018-02-27 12:29:59"
}

但实际上,当反馈细节中没有数据时,响应是:

    "feedback_details":[
]

反馈详情类:

public class FeedbackDetails {

@SerializedName("sales_remark")
private String salesRemark;

@SerializedName("account_id")
private String accountId;

@SerializedName("updated_at")
private String updatedAt;

@SerializedName("description")
private String description;

@SerializedName("created_at")
private String createdAt;

@SerializedName("id")
private String id;

@SerializedName("document_id")
private String documentId;

@SerializedName("lead_id")
private String leadId;

@SerializedName("lat")
private String lat;

@SerializedName("long")
private String longitude;

@SerializedName("reason_id")
private String reasonId;

@SerializedName("status")
private String status;

public void setSalesRemark(String salesRemark) {
    this.salesRemark = salesRemark;
}

public String getSalesRemark() {
    return salesRemark;
}

public void setAccountId(String accountId) {
    this.accountId = accountId;
}

public String getAccountId() {
    return accountId;
}

public void setUpdatedAt(String updatedAt) {
    this.updatedAt = updatedAt;
}

public String getUpdatedAt() {
    return updatedAt;
}

public void setDescription(String description) {
    this.description = description;
}

public String getDescription() {
    return description;
}

public void setCreatedAt(String createdAt) {
    this.createdAt = createdAt;
}

public String getCreatedAt() {
    return createdAt;
}

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

public String getId() {
    return id;
}

public void setDocumentId(String documentId) {
    this.documentId = documentId;
}

public String getDocumentId() {
    return documentId;
}

public void setLeadId(String leadId) {
    this.leadId = leadId;
}

public String getLeadId() {
    return leadId;
}

public void setLat(String lat) {
    this.lat = lat;
}

public String getLat() {
    return lat;
}

public void setJsonMemberLong(String longitude) {
    this.longitude = longitude;
}

public String getJsonMemberLong() {
    return longitude;
}

public void setReasonId(String reasonId) {
    this.reasonId = reasonId;
}

public String getReasonId() {
    return reasonId;
}

public void setStatus(String status) {
    this.status = status;
}

public String getStatus() {
    return status;
}

}

在使用Gson解析响应时的Retrofit中我收到此错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2889 path $.applicantDocumentPhotos[0].feedback_details

我使用过Gson Converter可以帮助解决它的问题。

3 个答案:

答案 0 :(得分:0)

在让Gson解析之前,您需要检查对象的类型。如果它是一个数组,您可能只想返回null值。

最简单的方法是实现自定义JsonDeserializer,例如:

public class FeedbackDetailsDeserializer
            implements  JsonDeserializer<FeedbackDetails> {

    private Gson gson = new GsonBuilder().setPrettyPrinting().create();
    @Override
    public FeedbackDetails deserialize(JsonElement json, Type typeOfT,
            JsonDeserializationContext context)
                throws JsonParseException {

        if(json.isJsonArray()) return null;
        return gson.fromJson(json, typeOfT);
    }

}

并在设置为Retrofit之前将其注册到Gson:

Gson gson = new GsonBuilder().setPrettyPrinting()
    .registerTypeAdapter(FeedbackDetails.class,
            new FeedbackDetailsDeserializer())
    .create();

另请注意,如果您的回复是(包含{&amp; }):

{
    "feedback_details":[
    ]
}

你需要一个包装类,如:

public class FeedbackDetailsResponse {
    public FeedbackDetails feedback_details;
}

并且您的Retrofit服务API将具有以下内容:

Call<FeedbackDetailsResponse> ...

答案 1 :(得分:0)

来自服务器端响应的这个问题。当数据可用时,它们发送对象,当数据为空时,它们发送数组。并且你需要告诉你的服务器端程序员在数据为空时发送对象。像这样&#34; feedback_details&#34;:{}而不是&#34; feedback_details&#34;:[]它将起作用。< / p>

答案 2 :(得分:0)

以下声明可能会帮助您!

JSONObject类型来自org.json。*不是Gson。您需要来自com.google.gson。*的JsonObject,还是要绑定到您自己的模型类。