JSON Message marshalling in spring-amqp

I’ve been doing a bit of exploration in spring-amqp lately and came across some of the built-in features to automatically marshall/unmarshall AMQP messages to java objects. Although you can get away with just having java objects implement Serializable but that just means you’ll only be dealing with java to java communication and that’ll break down the amount of flexibility you have.

Luckily there’s JsonMessageConverter, which allows you to marshal and unmarshal messages as JSON. By default this uses a _TypeID_ header which maps to the java class name. For this me this just didn’t work as I have an app in node.js communicating with a Consumer and Producer living in java land. The solution comes from a little undocumented feature.

Essentially you just need to set a map of class mappings on the java side of things:

Then assign it to the JsonMessageConverter you’ll be using to marshall messages… in this example it’s used for both a consumer and producer, but I’ll just focus on the consumer:

And the actual consumer (which is just a plain java object).

Now whatever messages get published will just refer to the _TypeId_ header to map json objects to classes behind the scenes (no JAXB annotations or anything needed). For example, publishing a message from node.js:

As a final note, I didn’t like the default header field _TypeId_. The only way to change this with the current API is to override getClassIdField in DefaultClassMapper to return the header field name you want to use. For my purposes I just changed this to the field type:

Pretty sweet stuff. Feel free to check out some of the examples in the github repository for this.

  • Holger

    Thanks for writing this down! It helped alot.

  • http://jcastaneyra.com Jose Castaneyra

    Thanks a lot, you saved me a lot of wasted hours!!

  • anujacharya

    This example is great but my consumer don’t put the type in “header”. Instead in the “Body” there is json, where there {“@type”:”Person” … } how to convert to Java object? Please any help valued