在Retrofit 2.0中检索JSON字段时出错 [英] Error on retrieving JSON field in Retrofit 2.0

查看:113
本文介绍了在Retrofit 2.0中检索JSON字段时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题. 我正在使用Retrofit 2.0从我的Android应用程序调用我的api.一切正常,但是当我收到一个空字段时,出现此错误:

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:

期望BEGIN_OBJECT,但在行1列8599路径处为BEGIN_ARRAY $ .meta.pagination.links

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?

这是我的全部答复:

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

这是我的POJO类:

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;
            }
        }

    }
}

推荐答案

我建议此处找到一些示例用法此处.

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

这篇关于在Retrofit 2.0中检索JSON字段时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆