We faced a similar sort of issue in our microservices communication. We had two services approval and transfer, so once a transfer is approved there will be a communication between the above services using Kafka, where the transfer will be the consumer.
Both the services are maintaining a common bean Payload, which has some fields as Object type
@Getter
@Setter
public class Payload extends KafkaParameters implements Serializable {
private static final long serialVersionUID = 1L;
private Object requestedBy;
private Object requestDetails;
private Object payload;
private Object existingPayload;
private Object payloadDifference;
}
Initially from the transfer service we'll set the value to the payload attribute inside Payload bean which will be a reference of type TransactionRequest. So, once the consumer in the transfer service is getting the callback from the approval service we are getting the Payload and when we tried to downcast we got this error
@Service
@Slf4j
public class AdjustmentApprovalConsumer {
@KafkaListener(topics = TransferConstants.ADJUSTMENT_APPROVAL_TOPIC, containerFactory = "ApprovalConcurrentKafkaListenerContainerFactory")
public void listenCdr(@org.springframework.messaging.handler.annotation.Payload Payload approvalRequest) {
TransactionRequest request = (TransactionRequest) approvalRequest.getPayload();
}
}
We fixed this issues by using two methods
- Convert the payload to a JSON string
public static String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
- Convert the JSON string to a given bean
public static <T> Object jsonToObject(final String json, Class<T> type) {
try {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(json, type);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
So the final code was like this
TransactionRequest request = (TransactionRequest) JsonUtils.jsonToObject(JsonUtils.asJsonString(approvalRequest.getPayload()), TransactionRequest.class);
This is may not be a conventional way of doing it but surely fixed the issue.
Account? Why are you trying to cast to it from a map?given()method is statically imported from?Accountis a model from Dropwizard which usescom.fasterxml.jackson.databind.annotations