【问题标题】:Expected BEGIN_OBJECT but was BEGIN_ARRAY : Retrofit2 Android预期为 BEGIN_OBJECT 但为 BEGIN_ARRAY :Retrofit2 Android
【发布时间】:2016-08-20 04:55:26
【问题描述】:

我是 JSON 解析的新手,正在尝试解析以下 JSON:

[
 {
"id" : 1,
"title" : {
    "rendered": "a link"
 },
"categories": [ 4,9,11 ],
"links":{
        "featuredmedia":[
        {
          "href": link
        }
           ]
    }
},
...
]

我的界面是:

public interface MediaAPI {
    @GET("Media")
    Call<LinkList> getDetails();
}

我的模型类是:

public class LinkList {
    private List<Links> links;
    // getter and setter    
}

...

public class Links {
  private List<Featuredmedia> Featured = new ArrayList<Featuredmedia>();
  // getter and setter 
 }

...

public class Featuredmedia {
    private String href;
    // getter and setter    
}

客户端代码是:

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ROOT_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    MediaAPI service = retrofit.create(MediaAPI.class);

    Call<LinkList> call = service.getDetails();
    call.enqueue(new Callback<LinkList>() {
        @Override
        public void onResponse(Call<LinkList> call, Response<LinkList> response) {
            if(response.isSuccessful()){                   
                successToast();
            }
            else {                                      
                failToast();
            }
        }

        @Override
        public void onFailure(Call<LinkList> call, Throwable t) {               
            Log.d("Failed", t.getMessage());
            showToast();

        }
    });

我只需要在“特色媒体”中获取链接,因此我只将这些链接包含在模型中。我也对here 的错误有所了解,但错误仍然存​​在。

任何解决此问题的建议都会有很大帮助。

【问题讨论】:

  • 而不是调用 getDetails(),尝试调用 getDetails()
  • 为了更好地理解 JSON,请read this link,并检查这些工具:formattereditor,它们极大地帮助(至少我)验证和“读取”数据是什么,以及什么这意味着...基本上[...]是数组,{...}是对象

标签: android json runtime-error retrofit2


【解决方案1】:

像这样更改Links 模型。

public class Links {
  private List<Featuredmedia> featuredmedia = new ArrayList<Featuredmedia>();
  // getter and setter 
 }

还有LinkList应该是这样的。

public class LinkList {
    private Links links;
    // getter and setter    
}

【讨论】:

    【解决方案2】:

    Gson 将负责将 json 反序列化到您的 LinksList 并期望有一个对象来实现这一点。

    您的模型基本上期望类似:

    {
       links: [...]
    }
    

    由于您的 Response Json 是一个数组,您希望有一个模型来表示它:任何 Array 或 List 都可以。

    所以不要使用 LinkList,只需使用例如Call&lt;List&lt;Links&gt;&gt;

    【讨论】:

      猜你喜欢
      • 2018-04-24
      • 2019-06-14
      • 2020-11-19
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 2014-08-01
      • 2015-11-26
      • 2018-03-27
      相关资源
      最近更新 更多