【问题标题】:Android - Retrofit exception Expected BEGIN_OBJECT but was BEGIN_ARRAYAndroid - 改造异常应为 BEGIN_OBJECT 但为 BEGIN_ARRAY
【发布时间】:2015-02-19 13:34:44
【问题描述】:

我是 GSON 和改造的新手,这是我的输出模型(仅供参考结构),

    public class Result1
    {
        public int TotalCount { get; set; }
    }

    public class Result2
    {
        public int PostId { get; set; }
        public int PostTypeId { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public bool IsFeatured { get; set; }
        public string Thumbnail { get; set; }
        public string CreatedDate { get; set; }
        public int CreatedBy { get; set; }
    }



public class RootObject
  {
     @Expose
        private List<com.example.got_sample.Result2> Result2 = new ArrayList<com.example.got_sample.Result2>();

    public List<com.example.got_sample.Result1> getResult1() {
        return Result1;
        }

        public void setResult1(List<com.example.got_sample.Result1> Result1) {
        this.Result1 = Result1;
        }

        public List<com.example.got_sample.Result2> getResult2() {
        return Result2;
        }
        public void setResult2(List<com.example.got_sample.Result2> Result2) {
        this.Result2 = Result2;
        }
    //Similar for result1
            }

这是我的输出

    [{"Result1":

[{"TotalCount":5}]},

    {"Result2":

    [{"PostId":6,"PostTypeId":1,"Title":"","Description":"something"..},{"PostId":7,"PostTypeId":1,"Title":"","Description":"something"..}]
    }]

这是我的改造代码

 postmethod.sendpostrequest(object, new Callback<RootObject>() {
                      @Override
                      public void failure(RetrofitError retrofitError) {
                          System.out.println(retrofitError.getMessage());
                      }

                    @Override
                    public void success(RootObject arg0,
                            retrofit.client.Response arg1) {
                        // TODO Auto-generated method stub

                    }
                  });

    This is the exception I get"

预期为 BEGIN_OBJECT,但为 BEGIN_ARRAY"

我尝试将 RootObject 替换为 List ,因为我只对结果 2 感兴趣。在这种情况下,我得到的响应为 null。请帮助。

【问题讨论】:

    标签: android gson retrofit


    【解决方案1】:

    您的 JSON 的根是 Result1 对象的数组,但您的 Callback 方法适用于单个 RootObject。

    尝试将您的 JSON 修改为以“{”开头并以“}”结尾,以使根成为对象而不是数组。

    【讨论】:

    • 感谢您的回复。有什么方法可以让我在不修改输出 JSON 的情况下让它工作吗?
    • 如果初始方括号内的 JSON 与 RootObject 的定义匹配,则将回调从 Callback 更改为 Callback> 将起作用。然后,您将在 List 的 0 位置查找您的 RootObject。
    • 仅将其更改为 List 有效!谢谢
    猜你喜欢
    • 2017-01-19
    • 2016-04-27
    • 2020-02-03
    • 1970-01-01
    • 2020-03-28
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 2014-08-01
    相关资源
    最近更新 更多