user2325154 user2325154 - 1 month ago 5
Java Question

Not able to typecast from String to a class in Spring REST

Getting following exception while hitting a Rest endpoint. How do I typecast from

String
to
ProtectPanReplyType
class?

Error:

Error - Request: http://localhost:9090/hosted-payments-webapp-1.0.0/pan/protect
raised java.lang.ClassCastException: com.gsicommerce.api.checkout.ProtectPanReplyType cannot be cast to java.lang.String


ProtectPanServiceImpl.java

@Service
public class ProtectPanServiceImpl implements ProtectPanService {

@Override
public ResponseEntity<?> sendProtectPanRequest(ProtectPan protectPan) {
String pan = protectPan.getPaymentAccountNumber();
String tenderClass = protectPan.getTenderClass();

String protectPanRequest = XMLHelper.createProtectPanRequest(pan, tenderClass);
System.out.println("protectPanRequest = " + protectPanRequest);
ResponseEntity<String> response = null;
try {
response = ApiClientUtils.callClientByEndpointandMessage(protectPanRequest, DEV_PUBLIC_API_URL,
ProtectPanReplyType.class);
System.out.println("response.getClass() = " + response.getClass());

//DOES NOT WORK
//ProtectPanReplyType protectPanReplyType = (ProtectPanReplyType)response.getBody();

//THROWS ClassCastException HERE
System.out.println(response.getBody());
} catch (JiBXException e) {
e.printStackTrace();
}
return response;
}

}


ApiClientUtils.java

public ResponseEntity<String> callClientByEndpointandMessage(String xmlRequest, String endpoint, Class<?> replyType) throws JiBXException {
HttpEntity<String> request = createRequestForUser("username", "secret",xmlRequest);
ResponseEntity<String> response = restOperations.postForEntity(endpoint, request, String.class);
ResponseEntity formattedResponse = new ResponseEntity(null, HttpStatus.BAD_REQUEST);
try {
Object jibxObject = JibxHelper.unmarshalMessage(response.getBody(), replyType);
formattedResponse = new ResponseEntity(jibxObject, HttpStatus.OK);
} catch (JiBXException e) {
FaultResponseType faultResponse = JibxHelper.unmarshalMessage(response.getBody(), FaultResponseType.class);
formattedResponse = new ResponseEntity(faultResponse, HttpStatus.BAD_REQUEST);
}
return formattedResponse;
}


ProtectPan.java

public class ProtectPan {

@JsonProperty("paymentAccountNumber")
private String paymentAccountNumber;

@JsonProperty("tenderClass")
private String tenderClass;

public String getPaymentAccountNumber() {
return paymentAccountNumber;
}

public String getTenderClass() {
return tenderClass;
}
}


ProtectPanReplyType.java

public class ProtectPanReplyType {

private String token;
private List<Element> anyList = new ArrayList<Element>();
private String sessionId;

//getters and setter removed for brevity
}

Answer
  1. Use ResponseEntity<ProtectPanReplyType> instead ResponseEntity<String>
  2. Build and Return ProtectPanReplyType from your restOperations.postForEntity()
Comments