[英]How to get data in this using retrofit
How to GET this type of JSON data using Retrofit ? 如何使用Retrofit获取此类JSON数据? How can I solve this issue?
我该如何解决这个问题?
MainActivity.java MainActivity.java
Api.getClient().getCategoryList(new Callback<List<Movie>>() {
@Override
public void success(List<Movie> movies, Response response) {
if (movies.get(0).getError().equalsIgnoreCase("false")) {
itemsList1=movies;
setCategorydataRecycle();
}
}
}
{
"error": false,
"category": [
{
"category_id": "1",
"category_name": "Adults",
"categroy_image": "assets/category-image/cat1.jpg"
},
{
"category_id": "2",
"category_name": "Kids",
"categroy_image": "assets/category-image/cat1.jpg"
},
{
"category_id": "3",
"category_name": "Gym",
"categroy_image": "assets/category-image/cat1.jpg"
}
]
}
If you look at the retrofit documentation, you need a few things to get it to work. 如果你看一下改装文档,你需要做一些事情来使它工作。
Here is our API 这是我们的API
interface API {
@GET("/movies")
Call<MovieResponse> retrieveMovies();
}
We have to create our movie response data object. 我们必须创建我们的电影响应数据对象。
class MovieResponse {
List<Movie> movies;
boolean error;
}
Now that we have a service, lets create a simple Retrofit factory which will create Retrofit for us. 现在我们有了服务,让我们创建一个简单的Retrofit工厂,它将为我们创建Retrofit。
public class RetrofitFactory {
private static final String BASE_URL = "www.myurl.com";
private Retrofit mRetrofit = null;
public static Retrofit create(){
if(mRetrofit == null){
return createRetrofit();
}
return mRetrofit;
}
private static Retrofit createRetrofit(){
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(createOkHttpClient())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
private static OkHttpClient createOkHttpClient(){
return new OkHttpClient().newBuilder().addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request.Builder builder = originalRequest.newBuilder().header("Authorization",
Credentials.basic("aUsername", "aPassword"));
Request newRequest = builder.build();
return chain.proceed(newRequest);
}
}).build();
}
}
Our Simple service class will be. 我们的简单服务类将是。
public class Services {
public static API getMoviesService(){
return RetrofitFactory.create().create(API.class);
}
}
Now that we have all the components we need for our system, below is how we glue it together. 既然我们拥有了系统所需的所有组件,下面就是我们如何将它们粘合在一起。
public class MoviesRepository {
public void retrieveMovies() {
API api = Services.getMoviesService();
Call <MovieResponse> call = api.retrieveMovies();
call.enqueue(new Callback<MovieResponse>() {
@Override
public void success(MovieResponse mvRes, Response response) {
// Get your error and movies list here
// mvRes.error;
//mvRes.movies
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.