【问题标题】:how to cast response to responseEntity如何将响应转换为 responseEntity
【发布时间】:2021-09-16 15:59:37
【问题描述】:

您好,我的服务出现问题,提示“发生内部服务器错误异常!异常详细信息:IdentificationResponse 无法转换为 org.springframework.http.ResponseEntity””对此事有何帮助?

下面是我的代码块;

我的身份识别服务实现;

Slf4j
@Service
@RequiredArgsConstructor
public class IdentificationServiceImpl implements IdentificationService {

    private final RestTemplate restTemplate;

    @Value("${platform.url}")
    private String platform;

    private final ServiceConfig serviceConfig;

    @Override
    public ResponseEntity<IdentificationResponse> createIdentification(Request request) {

        IdentificationRequest identificationRequest = new IdentificationRequest(serviceConfig.getIssuerKey(), serviceConfig.getSecureKey());

        identificationRequest.setOperation(ClientConstants.CREATE_IDENTIFICATION_ADD);

        HttpEntity<IdentificationRequest> requestHttpEntity = new HttpEntity<>(IdentificationRequest);

        ResponseEntity<IdentificationResponse> response = restTemplate.exchange(platform, HttpMethod.POST, requestHttpEntity, IdentificationResponse.class);

        return HandleResponse.handleResponse(response);
    }

下面是我的句柄响应类;

public static <T> T handleResponse(ResponseEntity response) {
        HttpStatus code = response.getStatusCode();
        if (code == HttpStatus.OK || code == HttpStatus.CREATED) {
            return (T) response.getBody();

        } else if (code == HttpStatus.NO_CONTENT) {
            return null;
        } else if (code == HttpStatus.BAD_REQUEST)
            throw new BadRequestException("BadRequest Exception occured while requesting! Exception details: " + response.getBody());
        else if (code == HttpStatus.UNAUTHORIZED)
            throw new UnauthorizedException("Unauthorized Exception occured while requesting! Exception details: " + response.getBody());
        else
            throw new HttpClientException("Exception occured! Exception details: " + response.getBody(), code.value());
    }
}

下面是我的 IdentificationRequest 类;

 @Data
 public class IdentificationRequest {

    @Setter(AccessLevel.NONE)
    @NotNull
    @JsonProperty("IssuerKey")
    private String issuerKey;
    @Setter(AccessLevel.NONE)
    @NotNull
    @JsonProperty("SecurityKey")
    private String secureKey;
    @NotNull
    @JsonProperty("TransactionId")
    private String transactionId;
    @NotNull
    @JsonProperty("TransactionDate")
    @DateTimeFormat(pattern = "YYYY-MM-DD HH:mm:ss.SSS")
    private String transactionDate;
    @NotNull
    @JsonProperty("Msisdn")
    @Pattern(regexp = "^905.{9}", message = "must be of 12 char/digit")
    private Long msisdn;
    private String operation;
    @NotNull
    @JsonProperty("Package")
    private String Package;
    @NotNull
    @JsonProperty("STB")
    private Boolean isStb;
    @JsonProperty("STB_SerialNumber")
    private String stbSerialNumber;
    @JsonProperty("STB_MacAddress")
    private String stbMacAddress;

    public IdentificationRequest(String issuerKey, String secureKey) {
        this.issuerKey = issuerKey;
        this.secureKey = secureKey;
    }
}

下面是我的请求类;

@Data
public class Request {
    @JsonProperty("OrderId")
    private String orderId;

    @JsonProperty("OrderItemId")
    private String orderItemId;

    @JsonProperty("ProcessInstanceId")
    private String processId;

    @JsonProperty("step_id")
    private String stepId;

    @JsonProperty("step_name")
    private String stepName;

下面是我的响应类;

@Data
public class IdentificationResponse {

    @JsonProperty("IsSuccessful")
    private Boolean isSuccessful;
    @JsonProperty("Code")
    private Integer code;
    @JsonProperty("Message")
    private String message;
    @JsonProperty("Data")
    private Object data;
}

我需要地图来响应响应实体吗?

【问题讨论】:

  • 应该是这样的:return new ResponseEntity&lt;&gt;(your_object, HttpStatus.OK);
  • 您好,谢谢您的回答,但我已返回句柄响应,我该怎么说?
  • 一个很好的方法是使用@ControllerAdvice。您可以处理所需的所有状态代码的异常。 An example
  • 你好,谢谢@FaramarzAfzali,但我的逻辑有点不同,所以我需要处理我的通用响应,所以我该怎么做

标签: spring spring-boot rest java-8 controller


【解决方案1】:

根据您的代码,当您调用 response.getBody() 方法时,您将获得 IdentificationResponse 并将其转换为 ResponseEntity这是抛出 ClassCastException

  if (code == HttpStatus.OK || code == HttpStatus.CREATED)
      return (T) response.getBody();

您可以直接返回 response 而不是 response.getBody() 来解决您的问题,或者如果您想要您的 createIdentification 方法返回 IdentificationResponse 实例

return HandleResponse.handleResponse(response, IdentificationResponse.class);

 public static <T> T handleResponse(ResponseEntity response, Class<T> type) {
        HttpStatus code = response.getStatusCode();
        if (code == HttpStatus.OK || code == HttpStatus.CREATED)
            return (T) response.getBody();
 }

您可以找到更多与泛型相关的信息here

【讨论】:

    【解决方案2】:

    基本上,您试图将一个对象转换为一个不兼容的对象,如果两个对象都实现相同的接口或对象的层次结构允许,则可以进行转换,如果无法实现此转换,最好根据您检索到的对象的值创建响应对象的实例。

    【讨论】:

    • Lauran,感谢您的回复,请您更改我的代码以便我理解
    • @johndeltana 你可以尝试这样的事情return ResponseEntity.ok(restTemplate.exchange(platform, HttpMethod.POST, requestHttpEntity, IdentificationResponse.class)); 准确地添加错误发生的位置也是一个好主意,堆栈跟踪显示错误起源的代码行。
    • 谢谢你,但我返回handleResponse 我可以把它放在哪里
    • 注释掉实际的返回行并用我上面提到的代码进行测试,然后也许你会更好地理解并获得正确更改代码的想法。
    • 谢谢 我已经可以回复了;但我喜欢在返回时处理我的 HandleResponse 类
    猜你喜欢
    • 2021-08-30
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 2015-08-29
    • 2015-06-07
    • 2012-02-08
    • 2023-02-08
    相关资源
    最近更新 更多