【问题标题】:How to convert retrofit response into json object如何将改造响应转换为 json 对象
【发布时间】:2018-04-05 10:40:27
【问题描述】:

我只是想知道如何将这个实际上是 JSON 响应的改造库响应转换为 JSON 对象,以便我可以在我的 android 应用程序中使用它来做某事,因为我无法对缓冲阅读器中的响应做任何事情.

public void getMe(){
    RestAdapter adapter = new RestAdapter.Builder()
            .setEndpoint(ROOT_URL)
            .build();

    myApi api = adapter.create(myApi.class);
    api.sendme(

            userEmail,
            rs,
            Team1,
            Team2,

            new retrofit.Callback<retrofit.client.Response>() {
                @Override
                public void success(retrofit.client.Response result, retrofit.client.Response response) {

                    BufferedReader reader = null;


                    try {

                        reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
                        if (!output.equals("")) {
                            output = reader.readLine();



                        }


                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void failure(RetrofitError error) {
                    // loading.dismiss();
                    Toast.makeText(Leaderboard.this, "", Toast.LENGTH_LONG).show();
                }
            }
    );


}

这里让我向服务器发送回复

public interface myApi {

@FormUrlEncoded
@POST("/myleaderboard.php")
void sendme(

        @Field("userEmail") String userEmail,
        @Field("rs") String rs,
        @Field("team1") String team1,
        @Field("team2") String team2,
        Callback<Response> callback);

 }

我收到 JSON 响应,我必须以某种方式将其存储在我的 android 代码中,无论是使用 JSON 对象还是其他任何东西(如果可能)。 请帮我解决这个问题

【问题讨论】:

    标签: android json post retrofit


    【解决方案1】:

    只需将 myAPI 代码更改为

    public interface myApi {
    
    @FormUrlEncoded
    @POST("/myleaderboard.php")
    void sendme(
    
            @Field("userEmail") String userEmail,
            @Field("rs") String rs,
            @Field("team1") String team1,
            @Field("team2") String team2,
            Callback<JsonObject> callback);
    
     }
    

    会直接返回JsonObject

    【讨论】:

    • 哦,这看起来很有希望让我检查一下
    • 我已经进行了必要的更改,我的 getme 函数现在看起来像这样
    • @Override public void success(JSONObject jsonObject, retrofit.client.Response response) { }
    • 是的,它会直接返回jsonobject,你甚至可以从respone.getString("")这样的响应中获取值
    • 接下来我需要做什么才能将该 json 响应存储到一个变量中,例如,请告诉我,因为我是 android 的新手
    【解决方案2】:

    使用GsonConverterFactory将传入的json转换为model/pojo类

    implementation 'com.squareup.retrofit2:converter-gson:LATEST_VERSION'
    

    请通过以下链接 Retrofit Library Tutorial

    Consuming-APIs-with-Retrofit

    【讨论】:

      【解决方案3】:

      使用此链接将您的 JSON 转换为 POJO,其中选择选项如下图所示 [http://www.jsonschema2pojo.org/

      你会得到一个 POJO 类来作为你的响应

      public class Result {
      
      @SerializedName("id")
      @Expose
      private Integer id;
      
      
      /**
      * 
      * @return
      * The id
      */
      public Integer getId() {
          return id;
      }
      
      /**
      * 
      * @param id
      * The id
      */
      public void setId(Integer id) {
          this.id = id;
      }
      

      然后使用这样的界面:

      @FormUrlEncoded
      @POST("/api/level")
      Call<Result> checkLevel(@Field("id") int id);
      

      添加依赖

          compile 'com.squareup.retrofit2:retrofit:2.3.0'
      compile 'com.squareup.retrofit2:converter-gson:2.+'
      

      并像这样调用:

      Call<Result> call = api.checkLevel(1);
      call.enqueue(new Callback<Result>() {
          @Override
          public void onResponse(Call<Result> call, Response<Result> response) {
              response.body(); // have your all data
              int id =response.body().getId();
              String userName = response.body().getUsername();
              String level = response.body().getLevel();
          }
      
          @Override
          public void onFailure(Call<Result> call, Throwable t) {
          }
      });
      

      要以 JSON 格式获取响应,请勿使用 Retrofit 中的 addConverterFactory(GsonConverterFactory.create())

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-20
        • 2017-10-17
        • 2021-08-27
        • 1970-01-01
        • 2021-07-03
        • 2014-12-08
        • 2018-07-26
        • 1970-01-01
        相关资源
        最近更新 更多