具有不同主体的GSON类(错误/无错误)

时间:2016-01-06 14:41:46

标签: java android gson retrofit

我希望error在它发生时获得。所以,为此,我在我的班级中为error添加了一个变量。我有一个“正常身体”的变量。

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,我还需要其他构造函数吗?

1 个答案:

答案 0 :(得分: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();
    }