1

I'm using Retrofit with POJO to send a signup screen, which usually works, but the answer has two different objects depending on whether the result is valid. Which are:

{
    "errors": {
        "nome": [
            "Campo obrigatório"
        ],
        "sobrenome": [
            "Campo obrigatório"
        ]
    }
}

and:

{
    "success": {
        "nome": [
            "Campo obrigatório"
        ],
        "sobrenome": [
            "Campo obrigatório"
        ]
    }
}

And my POJO:

public class PostCadastro {

@SerializedName("nome")
@Expose
private String nome;
@SerializedName("sobrenome")
@Expose
private String sobrenome;

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

public String getSobrenome() {
    return sobrenome;
}

public void setSobrenome(String sobrenome) {
    this.sobrenome = sobrenome;
}

How can I deal with these two responses?

Daniel Beltrami
  • 756
  • 9
  • 22

3 Answers3

3

Retrofit responses understand @SerializedName annotation

public class PostCadastroResponse {
    @SerializedName("succes")
    @Nullable
    PostCadastro successResponse;
    @SerializedName("errors")
    @Nullable
    PostCadastro errorResponse;
}

If error then errors will be not null and success otherwise.

But cleaner architecture could be when your server return proper code and proper errormessage in case of error. You could use standart Retrofit's isSuccessful in Response class

dilix
  • 3,761
  • 3
  • 31
  • 55
0

I'm assuming PostCadastro is the object you are using to receive the API response. In which case you don't have a variable named "errors" or a variable named "success" to receive the correct response.

The variable names in your response object need to match the first nodes in the JSON tree. In this case nome and sobrenome are subnodes of "errors" and "success" so retrofit will search for an instance variable in the response object named "errors" or "success", won't find it and the nome and sobrenome fields in your PostCadastro object will be null.

Ian D
  • 71
  • 6
0

If you've success status code for two responses you can create:

@SerializedName(value = "success", alternate = {"errors"})
@Expose
private PostCadastro postCadastro;

public PostCadastro getPostCadastro() {
    return postCadastro;
}

public void setPostCadastro(PostCadastro postCadastro) {
    this.postCadastro = postCadastro;
}

public static class PostCadastro {
    @SerializedName("nome")
    @Expose
    private List<String> nome;
    @SerializedName("sobrenome")
    @Expose
    private List<String> sobrenome;

    public List<String> getNome() {
        return nome;
    }

    public void setNome(List<String> nome) {
        this.nome = nome;
    }

    public List<String> getSobrenome() {
        return sobrenome;
    }

    public void setSobrenome(List<String> sobrenome) {
        this.sobrenome = sobrenome;
    }
}