改进响应数组或对象

5cg8jx4n  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(290)

im与api有两种不同的响应。然后判断对象,但如何将消息的内容返回到字符串?以下示例返回异常:

Exception: java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast

json响应:

{
    "success": true,
    "data": {
        "message": "User created",
    }
}

json响应:

{
    "success": false,
    "data": [
        {
            "code": "existing_user_login",
            "message": "User Exist !"
        }
    ]
}

型号:

public class Response {
    public Boolean success;
    public Object data;

    public Boolean isSuccess() { return success; }

    public String getMessage() {
        if (data instanceof Data) {
            return ((Data) data).getMessage();
        } else if (data instanceof List) {
            try {
                return ((List<Data>) data).get(0).getMessage();
            } catch (Exception e) {
                return null;
            }

        } else return null;
    }

    public class Data {
        public String code;
        public String message;
        public String getMessage() { return message; }
        public String getCode() { return code; }
    }
}
lb3vh1jj

lb3vh1jj1#

您可以得到如下消息:

public String getMessage() {
    if (data instanceof Data) {
        return ((Data) data).getMessage();
    } else if (data instanceof List) {
        try {
             return (String) ((LinkedTreeMap) ((List) data).get(0)).get("message");
        } catch (Exception e) {
            return null;
        }

    } else return null;
}

相关问题