2017-06-08 17 views
-3

普通のJSONObject jsonResponseでは、私は単にboolean success = jsonResponse.getBoolean("success");を使用します。今、私はRetrofitライブラリを使用する必要があります。 私は応答がGSON形式であることを知っています。だからこそ私のphpファイルの$response["success"]をどう扱うかを考え出すのが苦労しているのです。Retrofit 2でJSON {"success":true}を読む方法は?

私はこの試みた:

call.enqueue(new Callback<User_Account_Model>() { 
     @Override 
     public void onResponse(Call<User_Account_Model> call, Response<User_Account_Model> response) { 

      try { 
       JSONObject jsonResponse = new JSONObject(new Gson().toJson(response)); 
       boolean success = jsonResponse.getBoolean("success"); 
       Toast.makeText(MainActivity.this,String.valueOf(success),Toast.LENGTH_SHORT).show(); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

をしかし、何try and catch内なのは実行されないようです。トーストメッセージは表示されません。私の方法は正しいのか何かが欠落しているのか、まったく間違っているのか?

+1

'User_Account_Model'クラスを追加して、もしあればログも追加してください。 –

+0

User_Account_Modelには、文字列の電子メールとパスワードのみが含まれています。ログにはトラブルシューティングに使用する重要な詳細は表示されません。 –

答えて

0

のように追加onResponse方法で今

public class User_Account_Model{ 
    @Expose 
    private boolean success; 

    // Add Getter and setter for **success** 
} 

ようsuccessためUser_Account_Modelにキーを追加します。エンキュー方法。

call.enqueue(new Callback<MyResponse>() { 
    @Override 
    public void onResponse(Call<MyResponse> call, Response<MyResponse> response) { 

     try { 
       int statusCode = response.code(); 
       Log.d("Response Code: ", "status Code: " + statusCode); 
       if (response.isSuccessful()){ 
       MyResponse mResponse = response.body(); 
       } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

応答が1つのノード「成功」のみを含む場合、それは機能します。

+0

getSuccess()が呼び出されない場合、どのようにしてブール値の成功を得ることができますか? mResponseと同じです。 –

+0

これを使う - >ブール値成功= mResponse.getSuccess(); –

+0

ありがとう!出来た。 –

0

唯一のブール値を持つクラス

public class MyResponse{ 
    @SerializedName("success") 
    private boolean success; 

    public boolean getSuccess(){ 
    return success; 
    } 
    public void setSuccess(boolean _success){ 
    success = _success 
    } 

} 

はこのクラスを使用してください

try { 
    String json =response.body().string(); 
    JSONObject jsonResponse = new JSONObject(json); 
    boolean success = jsonResponse.getBoolean("success"); 
    Toast.makeText(MainActivity.this,String.valueOf(success),Toast.LENGTH_SHORT).show(); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 
+0

getSuccessの使い方は? –

関連する問題