如何从Retrofit的GET请求中正确获取JSON格式布尔响应?
Hey there, I see the issue you're facing—right now you're just calling toString() on the ResponseBody object, which gives you the OkHttp internal representation instead of the actual JSON response content. Let's fix this:
问题根源
ResponseBody.toString() doesn't return the raw response body text—it returns the object's string representation (like okhttp3.ResponseBody@xxxxxx). To get the actual JSON value your API returns, you need to read the content from the response body properly.
方案1:手动读取ResponseBody内容
修改你的onResponse方法,先确认请求成功,再读取响应体的字符串内容:
@Override public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) { if (response.isSuccessful() && response.body() != null) { try { // 读取响应体的原始字符串内容 String responseContent = response.body().string(); // 直接展示API返回的true/false Toast.makeText(MainActivity.this, responseContent, Toast.LENGTH_LONG).show(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(MainActivity.this, "Failed to parse response", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(MainActivity.this, "Request failed: " + response.code(), Toast.LENGTH_SHORT).show(); } }
⚠️ 注意:response.body().string()只能调用一次,因为它会消耗响应体的流。如果需要多次使用,记得先把内容保存到变量里。
方案2:让Retrofit自动解析为Boolean(更优雅)
既然你的API直接返回JSON格式的true或false,可以直接让Retrofit帮你解析成Boolean类型,省去手动处理字符串的麻烦:
首先修改你的接口:
public interface CheckUserInDBRequest { @GET("api/checkUserInDB.php") Call<Boolean> searchForUser( @Query("login") String login, @Query("pass") String pass ); }
然后更新调用代码:
Retrofit.Builder builder = new Retrofit.Builder() .baseUrl("https://kurusa.zhecky.net/") .addConverterFactory(GsonConverterFactory.create()); Retrofit retrofit = builder.build(); CheckUserInDBRequest client = retrofit.create(CheckUserInDBRequest.class); Call<Boolean> call = client.searchForUser( UserLogin.getText().toString(), UserPass.getText().toString() ); call.enqueue(new Callback<Boolean>() { @Override public void onResponse(@NonNull Call<Boolean> call, @NonNull Response<Boolean> response) { if (response.isSuccessful() && response.body() != null) { boolean userExists = response.body(); Toast.makeText(MainActivity.this, String.valueOf(userExists), Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "Request failed: " + response.code(), Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(@NonNull Call<Boolean> call, @NonNull Throwable t) { // 展示具体错误信息,方便排查问题 Toast.makeText(MainActivity.this, "Request failed: " + t.getMessage(), Toast.LENGTH_SHORT).show(); } });
这个方案更简洁,GsonConverter会自动把API返回的JSON布尔值转换成Java的Boolean对象,不用你手动处理字符串解析。
额外小提示
- 建议在
onFailure里展示具体的错误信息(比如t.getMessage()),而不是只显示"no ",这样能更快定位问题。 - 确保你的API确实返回纯JSON布尔值(
true或false),没有额外的字符或格式错误,否则Gson解析可能会失败。
内容的提问来源于stack exchange,提问作者Bipa

