We're going to look at sending JSON to RabbitMQ Queues in Spring AMQP with attention to Message Conversion. Before getting into it, let's read an excerpt from the Spring AMQP Guide on Message Conversion.
The default implementation of the MessageConverter strategy is called SimpleMessageConverter. This is the converter that will be used by an instance of RabbitTemplate if you do not explicitly configure an alternative. It handles text-based content, serialized Java objects, and simple byte arrays...If the content-type property value of the input Message is set to "application/x-java-serialized-object", the SimpleMessageConverter will attempt to deserialize (rehydrate) the byte array into a Java object. While that might be useful for simple prototyping, it’s generally not recommended to rely on Java serialization since it leads to tight coupling between the producer and consumer. It also rules out usage of non-Java systems on either side. With AMQP being a wire-level protocol, it would be unfortunate to lose much of that advantage with such restrictions.
Based on that advice using JSON is a preferable design choice rather than using the default serialization, so to use JSON message conversion we would define a jsonConverter in our RabbitTemplate.
With JSON conversion we could send our Reservation object to RabbitMQ...
...and handle it like this. Our local jsonToReservation() method uses fasterxml.jackson mapping to convert the JSON to a Reservation object.
When we look at our Message we see that Spring AMQP adds a __TypeId__ header to define the object type. If we read down to beginning of the sixth line we also see that the contentType of the Message is application/json.
We may not want to set JSON Conversion across the board for some reason, so we'll use Spring's Default Conversion and send JSON to the same Queue as before. Here is our Sender where we create a Message and place our JSON in the Message Body. Notice where we sent a Reservation object before we are now sending a Message.
Our Message contains the same JSON Body content and same application/json contentType, but no __TypeId__ Header as we did not add that to the Message we created.
Source code discussed in our Spring AMQP Series is found in NixMash RabbitMQ on GitHub. Code for this particular post is found in branch nixmashmq-v0.2.0 - Simple Producing and Consuming.