hanchen ke
hanchen ke

Reputation: 515

JsonSyntaxException Expected BEGIN_OBJECT but was BEGIN_ARRAY at path

I have my json as:

{
"status": "true",
"rows": [
    {
        "rec_time": "2017-05-02 11:08:00 "
    },
    {
        "rec_time": "2017-05-02 10:08:15 "
    }
],
"total": 10000,
"code": 200

}

My RowsBean model as:

public class RowsBean<T> extends BaseBean {


    private T rows;
    private int total;


    public T getRows() {
        return rows;
    }

    public void setRows(T rows) {
        this.rows = rows;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

}

public class DataBean {

    private String rec_time;

    public String getRec_time() {
        return rec_time;
    }

    public void setRec_time(String rec_time) {
        this.rec_time = rec_time;
    }

And my gson custom deserializer is as follows:

public class RowsJsonDeser implements JsonDeserializer<RowsBean<?>> {

    @Override
    public RowsBean<?> deserialize(JsonElement json, Type typeOfT,
                                     JsonDeserializationContext context) throws JsonParseException {

        RowsBean resultBean = new RowsBean();
        if (json.isJsonObject()) {
            JsonObject jsonObject = json.getAsJsonObject();

            Type type = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
           resultBean.setRows(context.deserialize(jsonObject.get("rows"),type));


        }
        return resultBean;
    }
}

I am using Retrofit library which uses gson to serialize/deserialize json objects. I pass this custom gson deserializer to retrofit but it gives me an error.

if jsonObject.get("rows") is jsonObject,The code is correct,but now, jsonObject.get("rows") is jsonArray

Error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at path $

Can you tell me where I am going wrong while desrializing?

Upvotes: 0

Views: 500

Answers (2)

Mapsy
Mapsy

Reputation: 4272

In addition to Mani's comment, I believe that you may come across further problems sincerows is an array of the row type, T. It looks like you should change your implementation of RowsBean to contain a rows type of T[], and not T.

Upvotes: 0

Mani
Mani

Reputation: 17595

Instead of jsonObject.get("rows"), use the below syndax

jsonObject.getAsJsonArray("rows")

Upvotes: 1

Related Questions