Search code examples
javaspring-bootspring-cloud-streamjackson2

can't parse my Json object received with binders in spring cloud stream


I have a problem with Json converter, I am sending a Json object in rabbitmq with spring cloud stream, when i try to listen to that object and convert it to a java object.

here is where i receive the object :


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.Ebanking.transactionservice.entities.Transaction;
import org.Ebanking.transactionservice.repositories.TransactionRepository;
import org.Ebanking.transactionservice.services.TransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;

@EnableBinding(Sink.class)
public class TransactionServiceImpl implements TransactionService {

    @Autowired
    TransactionRepository transactionRepository;


    @Override
    @StreamListener(target = Sink.INPUT)
    public void listen(String payload) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        Transaction transaction = mapper.readValue(payload,Transaction.class);
        transactionRepository.save(transaction);
        System.out.println("Transaction registered Successfully");
    }
}

here is from where i send the object :

    @StreamListener(target = Processor.INPUT)
    @SendTo(Processor.OUTPUT)
    public String processTransaction(Transaction transaction) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        Long idDebi = transaction.getAccountId();
        Long idCred = transaction.getAccountIdDestination();
        Double amount = transaction.getAmount();
        String str = mapper.writeValueAsString(transaction);
        if (debitAccount(idDebi, amount).equals(true) && creditAccount(idCred, amount).equals(true)) {
            processor.output().send(MessageBuilder.withPayload(str).setHeader("treatedTran","treatment").build());
            return "transaction treated successfully";
        }
        else return "transaction failed";
    } ```

Solution

  • ?

    You are not sending a Transaction object; you are simply sending Strings

    public String processTransaction(
            ...
            return "transaction treated successfully";
        }
        else return "transaction failed";