【问题标题】:Retrofit Response Array or Object either改造响应数组或对象
【发布时间】:2021-07-06 17:28:38
【问题描述】:

在第一种情况下,当它返回成功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; }
    }
}

【问题讨论】:

    标签: java android json jsonresponse


    【解决方案1】:

    可以先使用Object数据,在使用前判断,如下:

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

    【讨论】:

      【解决方案2】:

      使用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);
      

      【讨论】:

        猜你喜欢
        • 2021-12-09
        • 1970-01-01
        • 1970-01-01
        • 2019-06-03
        • 1970-01-01
        • 2019-08-01
        • 1970-01-01
        • 2021-03-15
        • 1970-01-01
        相关资源
        最近更新 更多