Error on retrieving JSON field in Retrofit 2.0 [duplicate]

半城伤御伤魂 提交于 2019-12-11 17:47:53

问题


I have a problem. I'm using Retrofit 2.0 to make calls to my api from my Android app. All works fine, but when I'm receive a empty field I get this error:

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 8599 path $.meta.pagination.links

The problem is with links field, that sometimes is not empty

"links": {
    "next": "http://www.example.com,
 }

But when it's empty the error appears. My questions, How can i handle when the links field is empty?

This is my whole response:

{
    "data": [
        {
        .....
        }
    ],      
    "meta": {
        "pagination": {
            "total": 50,
            "count": 50,
            "per_page": 60,
            "current_page": 1,
            "total_pages": 1,
            "links": []
        }
    }
}

And this my POJO class:

public class ListResponse<O> {

@SerializedName("data")
private List<O> lista;
@SerializedName("meta")
private Meta meta;

public List<O> getLista() {
    return lista;
}
public String getNext() { return meta.getPagination().getLinks().getNext(); }
public int getTotal() { return meta.getPagination().getTotal(); }

public class Meta {

    @SerializedName("pagination")
    Pagination pagination;

    public Pagination getPagination(){  return pagination; }

    public class Pagination{

        @SerializedName("total")
        int total;
        @SerializedName("count")
        int count;
        @SerializedName("per_page")
        int per_page;
        @SerializedName("current_page")
        int current_page;
        @SerializedName("total_pages")
        int total_pages;
        @SerializedName("links")
        Links links;

        public int getTotal() {
            return total;
        }

        public Links getLinks() {
            return links;
        }

        public class Links {
            @SerializedName("next")
            String next;

            public String getNext() {
                return next;
            }
        }

    }
}

回答1:


I would suggest JsonDeserializer. Some sample usage could be found here & here.



来源:https://stackoverflow.com/questions/51264561/error-on-retrieving-json-field-in-retrofit-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!