Ожидаемый BEGIN_ARRAY, но был BEGIN_OBJECT после дополнительного вызова - PullRequest
0 голосов
/ 01 июня 2019

Я знаю, что раньше об этом спрашивали, но я не могу найти решение в моем случае.Я запрашиваю ответ json о списке POJO (Movie)

. Хотя я впервые использую модификацию, у меня есть проблема в названии.URL, который я строю, является правильным, и ниже приведен пример ответа:

{  
   "page":1,
   "total_results":19850,
   "total_pages":993,
   "results":[  
      {  
         "vote_count":855,
         "id":420817,
         "video":false,
         "vote_average":7.2,
         "title":"Aladdin",
         "popularity":445.349,
         "poster_path":"\/3iYQTLGoy7QnjcUYRJy4YrAgGvp.jpg",
         "original_language":"en",
         "original_title":"Aladdin",
         "genre_ids":[  
            12,
            14,
            10749,
            35,
            10751
         ],
         "backdrop_path":"\/v4yVTbbl8dE1UP2dWu5CLyaXOku.jpg",
         "adult":false,
         "overview":"A kindhearted street urchin named Aladdin embarks on a magical adventure after finding a lamp that releases a wisecracking genie while a power-hungry Grand Vizier vies for the same lamp that has the power to make their deepest wishes come true.",
         "release_date":"2019-05-22"
      },
      {  
         "vote_count":5224,
         "id":299537,
         "video":false,
         "vote_average":7.1,
         "title":"Captain Marvel",
         "popularity":399.859,
         "poster_path":"\/AtsgWhDnHTq68L0lLsUrCnM7TjG.jpg",
         "original_language":"en",
         "original_title":"Captain Marvel",
         "genre_ids":[  
            28,
            12,
            878
         ],
         "backdrop_path":"\/w2PMyoyLU22YvrGK3smVM9fW1jj.jpg",
         "adult":false,
         "overview":"The story follows Carol Danvers as she becomes one of the universe’s most powerful heroes when Earth is caught in the middle of a galactic war between two alien races. Set in the 1990s, Captain Marvel is an all-new adventure from a previously unseen period in the history of the Marvel Cinematic Universe.",
         "release_date":"2019-03-06"
      },

Это моя модель

public class Movie implements Parcelable {


@PrimaryKey(autoGenerate = true)
private int id;
private String title;
private String releaseDate;
private String moviePoster;
private String avgVote;
private String plot;
private String movieId;
private String movieGenre;

@Ignore
public Movie(String title, String releaseDate, String moviePoster, String avgVote, String plot, String movieId, String movieGenre) {

    this.title = title;
    this.releaseDate = releaseDate;
    this.moviePoster = moviePoster;
    this.avgVote = avgVote;
    this.plot = plot;
    this.movieId = movieId;
    this.movieGenre = movieGenre;
}


public Movie(int id, String title, String releaseDate, String moviePoster, String avgVote, String plot, String movieId, String movieGenre) {

    this.id = id;
    this.title = title;
    this.releaseDate = releaseDate;
    this.moviePoster = moviePoster;
    this.avgVote = avgVote;
    this.plot = plot;
    this.movieId = movieId;
    this.movieGenre = movieGenre;

}

public String getMovieGenre() {
    return movieGenre;
}

public void setMovieGenre(String movieGenre) {
    this.movieGenre = movieGenre;
}

public int getId() {
    return id;
}

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

public String getTitle() {
    return title;
}

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

public String getReleaseDate() {
    return releaseDate;
}

public void setReleaseDate(String releaseDate) {
    this.releaseDate = releaseDate;
}

public String getMoviePoster() {
    return moviePoster;
}

public void setMoviePoster(String moviePoster) {
    this.moviePoster = moviePoster;
}

public String getAvgVote() {
    return avgVote;
}

public void setAvgVote(String avgVote) {
    this.avgVote = avgVote;
}


public String getPlot() {
    return plot;
}

public void setPlot(String plot) {
    this.plot = plot;
}

public String getMovieId() {
    return movieId;
}

public void setMovieId(String movieId) {
    this.movieId = movieId;
}



protected Movie(Parcel in) {
    title = in.readString();
    releaseDate = in.readString();
    moviePoster = in.readString();
    avgVote = in.readString();
    plot = in.readString();
    movieId = in.readString();
    movieGenre = in.readString();
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(title);
    dest.writeString(releaseDate);
    dest.writeString(moviePoster);
    dest.writeString(avgVote);
    dest.writeString(plot);
    dest.writeString(movieId);
    dest.writeString(movieGenre);
}

@SuppressWarnings("unused")
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
    @Override
    public Movie createFromParcel(Parcel in) {
        return new Movie(in);
    }

    @Override
    public Movie[] newArray(int size) {
        return new Movie[size];
    }
};

}

My @ GET

public interface JsonPlaceHolderApi {

    @GET("popular")
    Call<List<Movie>> getMovies(@Query("api_key") String api_key);
}

мой класс запроса данных

private static final String LOG_TAG = DataRequest.class.getSimpleName();

    ArrayList<Movie> mMovies = null;
    String jsonResponse = "";

    private DataInterface mListener;

    public DataRequest() {
        super();
    }

    public void  getData(String url)  {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.BASE_MOVIE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
        Call<List<Movie>> call = jsonPlaceHolderApi.getMovies(Constants.API_KEY);

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

               if(response!=null && response.body()!=null && mListener!=null){

                   mListener.responseData(response.body());
               }
            }
            @Override
            public void onFailure(Call<List<Movie>> call, Throwable t) {
                Log.d(LOG_TAG, "response code throwable " + t);
            }
        });
    }

    public void setOnDataListener(DataInterface listener) {
        mListener = listener;
    }

    public interface DataInterface {
        void responseData( List<Movie> myResponse );
    }
}

И наконец то, что я пытаюсь сделать в своей основной деятельности

prefSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                userOption = prefSpinner.getSelectedItem().toString();
                Log.d(LOG_TAG, "user option is "+ userOption);
                if (userOption.contentEquals("Most Popular") || userOption.contentEquals("Highest Rated")) {

                    DataRequest dataRequest = new DataRequest();
                    dataRequest.setOnDataListener(new DataRequest.DataInterface() {
                        @Override
                        public void responseData(List<Movie> myResponse) {
                            mMoviesList = myResponse;
                        }
                    });
                            dataRequest.getData(userOption);
                    movieRecycleViewAdapter.swapData(mMoviesList);

                } else if(userOption.contentEquals("Favorites")) {
                    setUpViewModel();
                    movieRecycleViewAdapter.notifyDataSetChanged();
                }
            }

1 Ответ

2 голосов
/ 01 июня 2019

Я запрашиваю JSON-ответ о списке POJO (Фильм)

Нет, вы не являетесь.Если вы посмотрите на вывод JSON, это объект JSON, а не массив JSON.Он содержит массив JSON в своем свойстве results.

Вам необходимо:

  • Создать класс Java, соответствующий структуре объекта JSON(который будет включать в себя поле List<Movie> results)

  • Измените Retrofit так, чтобы он возвращал Call<...>, где ... - это то, что вы называете классом Java, который вы создали в предыдущем пункте

...