Transformation returns null values
I’m using Retrofit, and I’m a rookie to Android.
My JSON response
{
"movie": {
"_id": "568661682d33bca267fdf81b",
"poster_path": "https://image.tmdb.org/t/p/w154/xHfhQIK4BNlsGv5Ylx8mVq0hJT1.jpg",
"adult": false,
"overview": "",
"release_date": "2015-05-15",
"id": 76341,
"original_title": "Mad Max: Fury Road",
"original_language": "en",
"title": "Mad Max: Furia en la carretera",
"vote_count": 3105,
"__v": 0,
"popular": true,
"production_companies": [],
"cast": [],
"genre_ids": [
53,
28,
12
]
}
}
Here is my movie model:
public class Movie {
public String Id;
more variables
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
more getter and setter
My Retrofit interface
public interface MyApiEndPointsInterface {
@GET("/movie/{id}")
Call<Movie> getMovie(@Path("id") int id);
}
and the code in the activity
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
MyApiEndPointsInterface apiService =
retrofit.create(MyApiEndPointsInterface.class);
Call<Movie> call = apiService.getMovie(76341);
call.enqueue(new Callback<Movie>() {
@Override
public void onResponse(Response<Movie> response, Retrofit retrofit) {
Log.d("MainActivity", response.body().title);
}
@Override
public void onFailure(Throwable t) {
}
});
I think it can be a JSON response because it has a high-level instance, but I don’t know how to use it in code.
I didn’t receive a response, is it all correct?
Solution
The problem is that the JSON parser does not expect an unnamed root object that wraps “movie” data in JSON.
If you can change the JSON returned by the server, delete the external object so that you only
have
{
"_id": "568661682d33bca267fdf81b",
"poster_path": "https://image.tmdb.org/t/p/w154/xHfhQIK4BNlsGv5Ylx8mVq0hJT1.jpg",
"adult": false,
"overview": "",
"release_date": "2015-05-15",
"id": 76341,
"original_title": "Mad Max: Fury Road",
"original_language": "en",
"title": "Mad Max: Furia en la carretera",
"vote_count": 3105,
"__v": 0,
"popular": true,
"production_companies": [],
"cast": [],
"genre_ids": [
53,
28,
12
]
}
If you cannot change the server’s response, there are several ways to handle it on the client side. I’ll simply create another object to map to the external JSON object, so leave the existing Movie class unchanged, add:
public class MovieResponse {
public Movie movie;
}
Then change the Retrofit call to use MovieResponse instead of Movie.
Then you can quote
movieResponse.movie