改装响应数组或对象

wpcxdonn  于 2021-08-25  发布在  Java
关注(0)|答案(2)|浏览(234)

在第一种情况下,当它返回成功时 true ,一切正常,成功的问题是 false ,然后返回错误:
如何改装响应数组或对象。

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 26 path $ .data

可以用一个响应类完成吗?
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 Data data;

    public Boolean isSuccess() { return success; }

    public Data getData() {
        return data;
    }

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

wd2eg0qa1#

您可以先使用对象数据,然后在使用之前对其进行判断,如下所示:

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

    public Boolean isSuccess() { return success; }

    public Object getData() {
        if(data instanceof Data){
            //do something
        }else if (data instanceof List) {
            //do something
        }else {
            //do something
        }
        return data;
    }

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

62o28rlo2#

使用 ObjectMapper 您可以通过如下配置反序列化功能来完成此操作:

// import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper objMapper = new ObjectMapper();
// this is to accept single element as array
objMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
// this is to handle if any property is missing
objMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Response resp = objMapper.readValue(jsonString, Response.class);

相关问题