改造 2:从响应正文中获取 JSON

新手上路,请多包涵

我想使用改造 2 从我的 api 获取字符串 json,使用改造 1 获取此 json 时我没有问题,但使用改造 2 为我返回 null

这就是我的 json 的样子

{"id":1,"Username":"admin","Level":"Administrator"}

这是我的 API

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

这就是我的代码的样子

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Config.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Api api = retrofit.create(Api.class);
        Call<ResponseBody> call = api.checkLevel(1);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                JsonObject post = new JsonObject().get(response.body().toString()).getAsJsonObject();
                    if (post.get("Level").getAsString().contains("Administrator")) {

                    }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });

我是改造 2 的新手,使用上面的代码,它总是让我的应用程序崩溃,因为 response.body().toString() 返回 null。

请指导我如何获取该 json 字符串,以便我可以将其转换为 JsonObject。

原文由 Dirus 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 586
2 个回答

使用此 链接 将您的 JSON 转换为 POJO,并使用下图中选择的选项

在此处输入图像描述

您将获得一个 POJO 类,用于您的响应,如下所示

public class Result {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("Username")
    @Expose
    private String username;
    @SerializedName("Level")
    @Expose
    private String level;

    /**
    *
    * @return
    * The id
    */
    public Integer getId() {
        return id;
    }

    /**
    *
    * @param id
    * The id
    */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
    *
    * @return
    * The username
    */
    public String getUsername() {
        return username;
    }

    /**
    *
    * @param username
    * The Username
    */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
    *
    * @return
    * The level
    */
    public String getLevel() {
        return level;
    }

    /**
    *
    * @param level
    * The Level
    */
    public void setLevel(String level) {
        this.level = level;
    }

}

并使用这样的界面:

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

并像这样调用:

 Call<Result> call = api.checkLevel(1);
call.enqueue(new Callback<Result>() {
    @Override
    public void onResponse(Call<Result> call, Response<Result> response) {
     if(response.isSuccessful()){
        response.body(); // have your all data
        int id =response.body().getId();
        String userName = response.body().getUsername();
        String level = response.body().getLevel();
        }else   Toast.makeText(context,response.errorBody().string(),Toast.LENGTH_SHORT).show(); // this will tell you why your api doesnt work most of time

    }

    @Override
    public void onFailure(Call<Result> call, Throwable t) {
     Toast.makeText(context,t.toString(),Toast.LENGTH_SHORT).show(); // ALL NETWORK ERROR HERE

    }
});

并在 Gradle 中使用依赖项

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

注意: 发生错误是因为您将 JSON 更改为 POJO(在改造中使用 addConverterFactory(GsonConverterFactory.create()) )。如果您想要 JSON 响应,请从 Retrofit 中删除 addConverterFactory(GsonConverterFactory.create()) 。如果没有,请使用上述解决方案

原文由 sushildlh 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以从原始对象获取 json 响应,就像您从 api 获取 ResponseBody

 Call<ResponseBody>

和内部回调你可以得到你的json响应

json = response.raw().toString();

原文由 Noah Mohamed 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题