我如何使用翻新从json中获取数据作为列表

时间:2018-12-25 11:11:12

标签: android json gson retrofit2 jsonschema2pojo

仅提取了一个数据,但是当我尝试以列表形式获取时,显示了问题预计会出现BEGIN_ARRAY,但是在第1行第2列路径$ 上出现了BEGIN_OBJECT 这是JSON链接:https://newsapi.org/v2/top-headlines?sources=abc-news&apiKey=4969854e2d424ed9972370f709ace9cc

这是我在MainActivity中获取JSON数据的方法

   private void loadJSON_Data() {

    RetofitClient_SingleTone 
      retofitClient_singleTone=RetofitClient_SingleTone.getInstance();


    Api api = retofitClient_singleTone.getApi();

    Call<List<Response_Pojo>> call = api.getAllResponse();

    call.enqueue(new Callback<List<Response_Pojo>>() {
        @Override
        public void onResponse(Call<List<Response_Pojo>> call, 
         Response<List<Response_Pojo>> response) {
            if (response.isSuccessful()) {

                Toast.makeText(context, "Success" + response.body().size(), 
           Toast.LENGTH_SHORT).show();
                Log.e("Home  - --", "onResponse: " + response.body());
                swipeRefreshLayout.setRefreshing(false);
            }
        }

        @Override
        public void onFailure(Call<List<Response_Pojo>> call, Throwable t) {
            Log.e("Home Failed - -", "Failed: " + t.getMessage());
            Toast.makeText(context, "Faield - - " +t.getMessage(), 
             Toast.LENGTH_SHORT).show();
            swipeRefreshLayout.setRefreshing(false);
        }
    });
}

这是我的api.Class

public interface Api {

@GET("top-headlines?sources=abc-news&apiKey=4969854e2d424ed9972370f709ace9cc")
Call<List<Response_Pojo>> getAllResponse();

}

RetofitClient_SingleTone类

public class RetofitClient_SingleTone {

  private static final String BASE_URL = "https://newsapi.org/v2/";
  private static RetofitClient_SingleTone mInstance;
  private Retrofit retrofit;

  private RetofitClient_SingleTone() {
    retrofit=new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
              .build();
 }
  public static synchronized  RetofitClient_SingleTone getInstance(){
    if (mInstance==null){
        mInstance = new RetofitClient_SingleTone();
    }
    return mInstance;
 }

 public Api getApi(){
    return retrofit.create(Api.class);
  }
}

这是我的POJO课

public class Response_Pojo {

@SerializedName("status")
@Expose
private String status;
@SerializedName("totalResults")
@Expose
private Integer totalResults;
@SerializedName("articles")
@Expose
private List<Article> articles = null;

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public Integer getTotalResults() {
    return totalResults;
}

public void setTotalResults(Integer totalResults) {
    this.totalResults = totalResults;
}

public List<Article> getArticles() {
    return articles;
}

public void setArticles(List<Article> articles) {
    this.articles = articles;
}
     public class Source {

    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("name")
    @Expose
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

   }

   public class Article {

    @SerializedName("source")
    @Expose
    private Source source;
    @SerializedName("author")
    @Expose
    private String author;
    @SerializedName("title")
    @Expose
    private String title;
    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("url")
    @Expose
    private String url;
    @SerializedName("urlToImage")
    @Expose
    private String urlToImage;
    @SerializedName("publishedAt")
    @Expose
    private String publishedAt;
    @SerializedName("content")
    @Expose
    private String content;

    public Source getSource() {
        return source;
    }

    public void setSource(Source source) {
        this.source = source;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUrlToImage() {
        return urlToImage;
    }

    public void setUrlToImage(String urlToImage) {
        this.urlToImage = urlToImage;
    }

    public String getPublishedAt() {
        return publishedAt;
    }

    public void setPublishedAt(String publishedAt) {
        this.publishedAt = publishedAt;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

   }

   }

3 个答案:

答案 0 :(得分:2)

在api服务界面中,您的响应应为Response_Pojo类,而不是List<Response_Pojo>,如下所示:

public interface Api {

@GET("top-headlines?sources=abc-news&apiKey=4969854e2d424ed9972370f709ace9cc")
Call<Response_Pojo> getAllResponse();

}

还需要相应地更改Calling API代码。

MainActivity.class:

private void loadJSON_Data() {
    RetofitClient_SingleTone 
      retofitClient_singleTone=RetofitClient_SingleTone.getInstance();


Api api = retofitClient_singleTone.getApi();

Call<Response_Pojo> call = api.getAllResponse();

call.enqueue(new Callback<Response_Pojo>() {
    @Override
    public void onResponse(Call<Response_Pojo> call, 
     Response<Response_Pojo> response) {
        if (response.isSuccessful()) {

            Toast.makeText(context, "Success" + response.body().getArticles().size(), 
       Toast.LENGTH_SHORT).show();
            Log.e("Home  - --", "onResponse: " + response.body());
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void onFailure(Call<Response_Pojo> call, Throwable t) {
        Log.e("Home Failed - -", "Failed: " + t.getMessage());
        Toast.makeText(context, "Faield - - " +t.getMessage(), 
         Toast.LENGTH_SHORT).show();
        swipeRefreshLayout.setRefreshing(false);
    }
});
}

请相应地更新代码,我尚未在IDE中对其进行编辑。

通过在 onResponse 方法中使用以下代码来从响应中获取列表:

@Override
    public void onResponse(Call<Response_Pojo> call, 
     Response<Response_Pojo> response) {
        if (response.isSuccessful()) {
          list = response.body().getArticles() // get the list from here

    }

答案 1 :(得分:0)

@GET(“ top-headlines?sources = abc-news&apiKey = 4969854e2d424ed9972370f709ace9cc”) 调用getAllResponse();

Retrofit Example you have to do small change..

答案 2 :(得分:0)

您需要替换

<List <Response_Pojo>> 

<Response_Pojo> 

如果要获取文章列表,可以从onResponse()回调方法中的response.body.getArticles()获取。