改造中的两种不同反应

Two Different Response in Retrofit

我正在使用 RetrofitPOJO 发送注册屏幕,这通常有效,但答案有两个不同的对象,具体取决于关于结果是否有效。它们是:

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

和:

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

还有我的 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;
}

我该如何处理这两个响应?

我假设 PostCadastro 是您用来接收 API 响应的对象。在这种情况下,您没有名为 "errors" 的变量或名为 "success" 的变量来接收正确的响应。

响应对象中的变量名称需要与 JSON 树中的第一个节点相匹配。在这种情况下,nome 和 sobrenome 是 "errors" 和 "success" 的子节点,因此 retrofit 将在名为 "errors" 或 "success" 的响应对象中搜索实例变量,不会找到它并且您的 PostCadastro 对象中的 nome 和 sobrenome 字段将为空。

改造响应理解@SerializedName注释

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

如果出错则不会出错 null 否则会成功。

但是当您的服务器 return 正确的代码和正确的错误消息以防出错时,架构可能更清晰。您可以在 Response class

中使用标准 Retrofit 的 isSuccessful

如果您有两个响应的成功状态代码,您可以创建:

@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;
    }
}