我想使用改造 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。
最佳答案
使用这个link使用下图中选择的选项将您的 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())
。如果没有,则使用上述解决方案
https://stackoverflow.com/questions/40973633/