2017-01-30 25 views
-1

當我將我的json錯誤響應從改造轉換爲對象時,我變空了。gson.fromJson正在返回null android的改造和gson

JSON字符串:

{"messageType":1,"hasErrors":true,"isSuccess":false,"message":"Invalid username or password"} 

我創建的類:

public class ValidationContainer { 


@SerializedName("messageType") 
@Expose 
private int MessageType; 

@SerializedName("hasErrors") 
@Expose 
private Boolean HasErrors; 

@SerializedName("isSuccess") 
@Expose 
private Boolean IsSuccess; 

@SerializedName("message") 
@Expose 
private String Message; 


public ValidationContainer() { 
} 

public String getMessage() { 
    return Message; 
} 

public void setMessage(String message) { 
    this.Message = message; 
} 

}

我的代碼:

  public void onResponse(Call<UserDTO> call, Response<UserDTO> response) { 

       if (response.isSuccessful()) { 
        //TODO: Save response user properties to shared constants 

        Intent intent = new Intent(getBaseContext(), MainActivity.class); 
        startActivity(intent); 
        finish(); 
       } else if (response.code() == 400) { 

        Gson gson = new GsonBuilder().create(); 
        ValidationContainer container = new ValidationContainer(); 

        try { 
         Log.e(Tag, response.errorBody().string()); 
         container = gson.fromJson(response.errorBody().string(), ValidationContainer.class); 

         Log.e(Tag, container.getMessage()); 

        } catch (IOException e) { 

         Log.e(Tag, e.getMessage()); 

        } 
       } 
      } 

當我登錄response.errorBody().string()我得到如下:

enter image description here

在的build.gradle

compile 'com.squareup.retrofit2:retrofit:2.1.0' 
compile 'com.squareup.retrofit2:converter-gson:2.1.0' 
compile 'com.google.code.gson:gson:2.6.1' 

我在做什麼錯?

+0

嘗試UserDTO'改變''到後ValidationContainer'也試試。 –

+0

@DheerubhaiBansal但我想轉換錯誤不是成功響應 –

+0

請將您的庫版本更改爲'com.google.code.gson:gson:2.6.2' –

回答

1

找到了解決方案,基於此鏈接:https://futurestud.io/tutorials/retrofit-getting-started-and-android-client

public void onResponse(Call<UserDTO> call, Response<UserDTO> response) { 

    if (response.isSuccessful()) { 
     //TODO: Save response user properties to shared constants 

     Intent intent = new Intent(getBaseContext(), MainActivity.class); 
     startActivity(intent); 
     finish(); 

    } else if (response.code() == 400) { 

     Converter<ResponseBody, ValidationContainer> converter = 
       retrofit.responseBodyConverter(ValidationContainer.class, new Annotation[0]); 

     try { 
      ValidationContainer error = converter.convert(response.errorBody()); 

      Toast.makeText(getBaseContext(), error.getMessage(), Toast.LENGTH_LONG).show(); 

     } catch (Exception e) { 
      Log.d(Tag, e.getMessage()); 
     } 

    } 
} 
-1

,請複製粘貼實際的代碼,因爲我不認爲GSON解析需要解析,我可以看到你正在使用它的任何IO異常。

去除if (response.code() == 400)

+0

你是什麼意思發表實際的代碼 - 代碼張貼在問題是實際代碼 –

0

請後出現在日誌中的錯誤消息,最初我還以爲你要實現Serializable接口

public class ValidationContainer implements Serializable { 

} 
+0

有沒有錯誤信息 –

+0

它工作?如果不是,請嘗試刪除@Expose –