【问题标题】:How to get response my below api when using retrofit?使用改造时如何得到我下面的 api 的响应?
【发布时间】:2017-12-21 09:13:33
【问题描述】:

我在使用 volley 或 bridge 时得到了 json 响应,但我无法使用改造库得到响应 以下是我的 API 我的 API https://api.myjson.com/bins/u88lj

我的代码如下

private void loadJSON(){
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://api.learn2crack.com")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RequestInterface request = retrofit.create(RequestInterface.class);
    Call<JSONResponse> call = request.getJSON();
    call.enqueue(new Callback<JSONResponse>() {
        @Override
        public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {

            JSONResponse jsonResponse = response.body();
            System.out.println("jsonResponse------------------"+jsonResponse );
            System.out.println("cancel()------------------" +jsonResponse.getAndroid());
            System.out.println("response------------------" +response);
            data = new ArrayList<>(Arrays.asList(jsonResponse.getAndroid()));
            adapter = new DataAdapter(data);
            recyclerView.setAdapter(adapter);
        }

        @Override
        public void onFailure(Call<JSONResponse> call, Throwable t) {
            Log.d("Error",t.getMessage());
        }
    });
}

【问题讨论】:

  • 你试过什么?把你的代码和错误
  • 分享你的代码和错误日志
  • DIY 像这样:1)转到how to make a pojo class from json response,2)将您的回复粘贴到那里并输入包和类名,3)选择目标语言为Java,4 ) 源类型为 Json,5) 注释样式为 Gson,6) 单击 Preview,7) 将这些类复制并粘贴到您的应用程序包中 8) 将 List&lt;RestResponse&gt; 用作 Call 的参数化类型。
  • @Shameem Ahsan,你能检查我的答案吗?

标签: android json android-recyclerview retrofit


【解决方案1】:

根据你的json数据。你的json是JSONArray

否则会出错

预期为 BEGIN_OBJECT,但为 BEGIN_ARRAY

您可以在代码中使用List&lt;JSONResponse&gt; 代替JSONResponse

Call<List<JSONResponse>> call = request.getJSON();

【讨论】:

    【解决方案2】:

    看看这个

    在界面中进行这样的更改

    public interface RetrofitInterface{
      @GET("url tail part")
        Call<ApiResponses> getApiResponses();
    }
    

    添加一个新的模型类

     public class ApiResponses {
    
            List<String> messages;
            List<ResultDetails> resultDetailsList;
    
            public ApiResponses(List<String> messages, List<ResultDetails> resultDetailsList) {
                this.messages = messages;
                this.resultDetailsList = resultDetailsList;
            }
    
            public List<String> getMessages() {
                return messages;
            }
    
            public List<ResultDetails> getResultDetailsList() {
                return resultDetailsList;
            }
    
    
    
            public static class ResultDetails{
    
                String name;
                String alpha2_code;
                String alpha3_code;
    
                public ResultDetails(String name, String alpha2_code, String alpha3_code) {
                    this.name = name;
                    this.alpha2_code = alpha2_code;
                    this.alpha3_code = alpha3_code;
                }
    
                public String getName() {
                    return name;
                }
    
                public String getAlpha2_code() {
                    return alpha2_code;
                }
    
                public String getAlpha3_code() {
                    return alpha3_code;
                }
            }
        }
    

    在主要活动中添加这个

     Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.learn2crack.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    
    retrofit.create(RetrofitInterface.class);
    retrofit.getApiResponses().enqueue(new Callback<ApiResponses>{
     @Override
                public void onResponse(Call<ApiResponses> call, Response<ApiResponses> response) {
    
                }
    
                @Override
                public void onFailure(Call<ApiResponses> call, Throwable t) {
    
                    call.cancel();
                    t.printStackTrace();
                }
    });
    

    【讨论】:

      【解决方案3】:

      像这样使用基本网址“https://api.myjson.com

          Retrofit retrofit = new Retrofit.Builder()
                  .baseUrl("https://api.myjson.com")
                  .addConverterFactory(GsonConverterFactory.create())
                  .build();
          RequestInterface request = retrofit.create(RequestInterface.class);
      

      创建这样的接口

      public interface RequestInterface {
      @GET("bins/u88lj")
      Call<JSONResponse> getJSON();
      
      }
      

      像这样在 json 中解析您的响应

      public class JSONResponse {
      
      @SerializedName("RestResponse")
      private RestResponse RestResponse;
      
      
      public JSONResponse.RestResponse getRestResponse() {
          return RestResponse;
      }
      
      public void setRestResponse(JSONResponse.RestResponse restResponse) {
          RestResponse = restResponse;
      }
      
      public class RestResponse {
          @SerializedName("messages")
          private ArrayList<String> messages;
      
          @SerializedName("result")
          private ArrayList<Result> result;
      
      
          public ArrayList<String> getMessages() {
              return messages;
          }
      
          public void setMessages(ArrayList<String> messages) {
              this.messages = messages;
          }
      
          public ArrayList<Result> getResult() {
              return result;
          }
      
          public void setResult(ArrayList<Result> result) {
              this.result = result;
          }
      }
      
      
      public class Result {
          @SerializedName("name")
          private String name;
          @SerializedName("alpha2_code")
          private String alpha2_code;
          @SerializedName("alpha3_code")
          private String alpha3_code;
      
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public String getAlpha2_code() {
              return alpha2_code;
          }
      
          public void setAlpha2_code(String alpha2_code) {
              this.alpha2_code = alpha2_code;
          }
      
          public String getAlpha3_code() {
              return alpha3_code;
          }
      
          public void setAlpha3_code(String alpha3_code) {
              this.alpha3_code = alpha3_code;
          }
      }
      
      }
      

      【讨论】:

        【解决方案4】:

        试试这个:

        Example.java

        public class Example {
        
            @SerializedName("RestResponse")
            @Expose
            private RestResponse restResponse;
        
            public RestResponse getRestResponse() {
                return restResponse;
            }
        
            public void setRestResponse(RestResponse restResponse) {
                this.restResponse = restResponse;
            }
        
        }
        

        RestResponse.java

        public class RestResponse {
        
            @SerializedName("messages")
            @Expose
            private List<String> messages = null;
            @SerializedName("result")
            @Expose
            private List<Result> result = null;
        
            public List<String> getMessages() {
                return messages;
            }
        
            public void setMessages(List<String> messages) {
                this.messages = messages;
            }
        
            public List<Result> getResult() {
                return result;
            }
        
            public void setResult(List<Result> result) {
                this.result = result;
            }
        
        }
        

        结果.java

        public class Result {
        
            @SerializedName("name")
            @Expose
            private String name;
            @SerializedName("alpha2_code")
            @Expose
            private String alpha2Code;
            @SerializedName("alpha3_code")
            @Expose
            private String alpha3Code;
        
            public String getName() {
                return name;
            }
        
            public void setName(String name) {
                this.name = name;
            }
        
            public String getAlpha2Code() {
                return alpha2Code;
            }
        
            public void setAlpha2Code(String alpha2Code) {
                this.alpha2Code = alpha2Code;
            }
        
            public String getAlpha3Code() {
                return alpha3Code;
            }
        
            public void setAlpha3Code(String alpha3Code) {
                this.alpha3Code = alpha3Code;
            }
        
        }
        

        API 客户端:

        public class ApiClient {
        
            public static final String BASE_URL = "https://api.myjson.com/";
            private static Retrofit retrofit = null;
        
        
            public static Retrofit getClient() {
                if (retrofit==null) {
                    retrofit = new Retrofit.Builder()
                            .baseUrl(BASE_URL)
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();
                }
                return retrofit;
            }
        }
        

        API接口:

        public interface ApiInterface {
        
            @POST("login.php")
            @FormUrlEncoded
            Call<users> getTopRatedMovies(@Field("uemail") String uemail, @Field("upassword") String upassword);
        
            @GET("bins/u88lj")
            Call<Example> getResponse();
        
            @Multipart
            @POST("create_event1.php")
            Call<users> uploadImage(@Part MultipartBody.Part image , @Part("user_email") RequestBody email,  @Part("e_name") RequestBody name);
        
        }
        

        主要活动:

         Call<Example> call = apiService.getResponse();
        
                // Set up progress before call
                final ProgressDialog progressDoalog;
                progressDoalog = new ProgressDialog(MainActivity.this);
                progressDoalog.setMessage("Its loading....");
                progressDoalog.setTitle("Please wail while data is loading");
                // show it
                progressDoalog.show();
        
        
        
                call.enqueue(new Callback<Example>() {
                    @Override
                    public void onResponse(Call<Example> call, Response<Example> response) {
                        progressDoalog.dismiss();
                        int statusCode = response.code();
        
                        // String movies = response.body().getMessage();
                        List<Result> restResponses = response.body().getRestResponse().getResult();
        
                        Log.w("response",new GsonBuilder().setPrettyPrinting().create().toJson(response));
                        recyclerView.setAdapter(new MoviesAdapter(restResponses, R.layout.list_item_movie, getApplicationContext()));
                    }
        
                    @Override
                    public void onFailure(Call<Example> call, Throwable t) {
                        progressDoalog.dismiss();
                        // Log error here since request failed
                        Log.e(TAG, t.toString());
                    }
                });
        

        适配器:

        public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MovieViewHolder> {
        
            private List<Result> movies;
            private int rowLayout;
            private Context context;
        
        
            public static class MovieViewHolder extends RecyclerView.ViewHolder {
                LinearLayout moviesLayout;
                TextView movieTitle;
                TextView data;
                TextView movieDescription;
                TextView rating;
        
        
                public MovieViewHolder(View v) {
                    super(v);
                    moviesLayout = (LinearLayout) v.findViewById(R.id.movies_layout);
                    movieTitle = (TextView) v.findViewById(R.id.title);
                    data = (TextView) v.findViewById(R.id.subtitle);
                    movieDescription = (TextView) v.findViewById(R.id.description);
                    rating = (TextView) v.findViewById(R.id.rating);
                }
            }
        
            public MoviesAdapter(List<Result> movies, int rowLayout, Context context) {
                this.movies = movies;
                this.rowLayout = rowLayout;
                this.context = context;
            }
        
            @Override
            public MoviesAdapter.MovieViewHolder onCreateViewHolder(ViewGroup parent,
                                                                    int viewType) {
                View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
                return new MovieViewHolder(view);
            }
        
        
            @Override
            public void onBindViewHolder(MovieViewHolder holder, final int position) {
                holder.movieTitle.setText(movies.get(position).getAlpha2Code());
                holder.data.setText(movies.get(position).getAlpha3Code());
                holder.movieDescription.setText(movies.get(position).getName());
        //        holder.rating.setText(movies.get(position).getVoteAverage().toString());
            }
        
            @Override
            public int getItemCount() {
                return movies.size();
            }
        }
        

        【讨论】:

        • 只需创建两个布局。一个有recyclerview,另一个是自定义行文件。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-15
        • 2021-02-06
        • 1970-01-01
        • 1970-01-01
        • 2021-08-19
        • 1970-01-01
        相关资源
        最近更新 更多