Class JsonCodec

java.lang.Object
org.acemq.amqp.codec.json.JsonCodec
All Implemented Interfaces:
Codec

public final class JsonCodec extends Object implements Codec
Reads and writes JSON, using Jackson.

What a publisher uses unless told otherwise, because an application publishing an object means to publish the object rather than whatever its toString produces.

Two settings of the default mapper are decisions rather than taste, and both are about messages outliving the code that wrote them.

Unknown properties are ignored. A producer that adds a field must not break every consumer deployed before it; refusing the message would make every additive change a release coordinated across teams, which is the coupling messaging exists to avoid.

Dates are written as ISO-8601 text rather than as numbers. A timestamp of 1735689600 needs a shared assumption about units and epoch to read; 2025-01-01T00:00:00Z does not, which matters when the consumer is in Go or Python and reading a millisecond count as seconds puts a message fifty thousand years in the past.

An application with its own configured mapper should pass it, so that messages match what the rest of the service produces.

  • Constructor Details

    • JsonCodec

      public JsonCodec()
      Uses a mapper configured as described above.
    • JsonCodec

      public JsonCodec(com.fasterxml.jackson.databind.ObjectMapper mapper)
      Parameters:
      mapper - the mapper to use; take care that it tolerates unknown properties, or a producer adding a field will start rejecting messages at every consumer
  • Method Details

    • defaultMapper

      public static com.fasterxml.jackson.databind.ObjectMapper defaultMapper()
      Returns:
      a mapper configured for messages that outlive the code that wrote them
    • contentType

      public String contentType()
      Specified by:
      contentType in interface Codec
      Returns:
      the content type this codec produces, for example application/json
    • encode

      public byte[] encode(Object payload)
      Specified by:
      encode in interface Codec
      Parameters:
      payload - object to encode; never null
      Returns:
      encoded bytes
    • decode

      public <T> T decode(byte[] body, Class<T> target)
      Specified by:
      decode in interface Codec
      Type Parameters:
      T - target type
      Parameters:
      body - encoded bytes
      target - type to produce
      Returns:
      the decoded payload
    • canDecode

      public boolean canDecode(@Nullable String contentType)
      Specified by:
      canDecode in interface Codec
      Parameters:
      contentType - content type of a received message, or null when the sender did not set one
      Returns:
      whether this codec can decode it
    • toString

      public String toString()
      Overrides:
      toString in class Object