2016-01-06 70 views
0

我想在发生碰撞时获得error。所以,为此我在我的班级中加入了一个变量error。我有一个“正常身体”的变量。GSON Class with different body(Error/NoError)

public class User { 
    @SerializedName("error") 
    public Error ErrorUser; 

    @SerializedName("infos") 
    public Infos Infos; 

    public class Infos { 
     @SerializedName("login") 
     public String Login; 

     @SerializedName("lastname") 
     public String LastName; 

     @SerializedName("firstname") 
     public String FirstName; 

     @SerializedName("email") 
     public String Email; 

     @SerializedName("internal_email") 
     public String EmailIntern; 

     @SerializedName("location") 
     public String Location; 

     @SerializedName("netsoul") 
     public String Netsoul; 

     @SerializedName("studentyear") 
     public int SchoolYear; 

     public Infos(String login, 
        String lastname, 
        String firstName, 
        String email, 
        String emailIntern, 
        String location, 
        String netsoul, 
        int schoolYear){ 
      this.Login = login; 
      this.LastName = lastname; 
      this.FirstName = firstName; 
      this.Email = email; 
      this.EmailIntern = emailIntern; 
      this.Location = location; 
      this.Netsoul = netsoul; 
      this.SchoolYear = schoolYear; 
     } 
    } 

    public User(Error error){ 
     Log.d("Here", "Work"); 
     this.ErrorUser = error; 
    } 

    public User(Infos infos){ 
     this.Infos = infos; 
    } 
} 

随着正常的身体(相关信息类)的工作,但是当我试图让错误的时候,它的发生,我得到user.ErrorUser on reference null object。所以我认为user是空的,但我不知道为什么。

呼叫

ApiService.getApiService().getInformationUser(SessionManager.getInstance().getToken()).enqueue(new Callback<User>() { 
      @Override 
      public void onResponse(Response<User> response, Retrofit retrofit) { 
       User user = response.body(); 
       if (user.ErrorUser == null) 
        Log.d("Here", user.Infos.FirstName); 
       else 
        Log.d("Here", user.ErrorUser.Message); 
      } 

      @Override 
      public void onFailure(Throwable t) { 

      } 
     }); 

错误类

public class Error { 
    @SerializedName("error") 
    public String Message; 

    @SerializedName("code") 
    public int Code; 

    public Error(String message, int code){ 
     this.Message = message; 
     this.Code = code; 
    } 
} 

如果messagecode有时倒,我需要另一个构造函数?

+0

http://stackoverflow.com/questions/31516581/retrofit-handle-json-key-which-has-a-dynamic-structure-array-object的可能的复制 –

+0

这是不完全一样probleme。 –

回答

0

我用字符串解决了它,包含错误代码和消息的response.errorBody()。我将它与GsonConverter()转换为我的类错误。

try { 
     Error error = (Error) GsonConverterFactory.create().fromResponseBody(Error.class, Error.class.getAnnotations()).convert(response.errorBody()); 
     Toast.makeText(this.login.getApplicationContext(), error.errorBody.Message, Toast.LENGTH_LONG).show(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    }