0

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?

2 Answers 2

1

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

jsonObject.getAsJsonArray("rows")

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer is the perfect solution to my problem,Thank you
0

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.

1 Comment

thank you for your help,I improved the code and used it in the implementation class 。like this Observable<RowsBean<List<DataBean>>>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.