Stefan Kendall
Stefan Kendall

Reputation: 67802

Using a custom marshaller in Jackson without annotations?

I need to use Jackson to marshal and unmarshal json on arbitrary objects, and I need a certain date format.

Right now, I have this:

final ObjectMapper mapper = new ObjectMapper()
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)

When I run mapper.writeValueAsString([a:new Date()]), I get a timestamp. My previous marshaling solution used this:

ISODateTimeFormat.dateTime().withZoneUTC().print(it.getTime())

but I can only seem to find a way to set a specific marshaller in Jackson with annotations. I have multiple classes for which I need particular marshaling, none of which can be annotated. Is there a way to set up marshaler by class?

Upvotes: 2

Views: 2459

Answers (1)

Stefan Kendall
Stefan Kendall

Reputation: 67802

Create a module, and add serializers to it for each type.

class ApiDateSerializer extends JsonSerializer<Date> {
    void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) {
        String dateString = ISODateTimeFormat.dateTime().withZoneUTC().print(date.getTime())
        jsonGenerator.writeString(dateString);
    }
}
...
  mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)
        Module queryModule = new SimpleModule("QueryModule", new Version(1, 0, 0, null))
        queryModule.addSerializer(Date.class, new ApiDateSerializer());
        mapper.registerModule(queryModule)

Upvotes: 3

Related Questions