Maroš Šeleng Maroš Šeleng - 1 month ago 11
JSON Question

Jackson's @JsonAppend with default value

guys! I am developing a web application and I decided to use Jackson as my JSON processing framework.

In request data that I am willing to send; let's say the POJO looks like this:

data class JSONEnvelope(
@JsonProperty("obj1")
val obj1: Obj1,

@JsonProperty("obj2")
val obj2: Obj2)


which get serialized like this:

{
"obj1":{...},
"obj2":{...}
}


but I need to add some metadata to that object, let's say fields
meta1
and
meta
. I thought that
@JsonAppend
would solve my problem, but I am using Jackson together with Jersey, so I am not serializing objects manually, so I cannot use
writer.withAttribute("...", ...)
.

I am aware of this thread, but there is no answer that kinda satisfy my needs, because I think, that writing a custom serializer is a bit overkill for this, moreover if I do not have a mechanism to "serialize the rest of the original object". I'd be glad for any ideas

Answer Source

The solution in the answer you cited, which adds a mixIn to a the ObjectMapper then uses the ObjectWriter to configure it, is a good solution.

For Jersey, which calls ObjectMapper.writerFor and therefore prevents you from calling withAttribute in order to configure the ObjectWriter, one alternative is to add the attribute to the ObjectWriter before returning it from writerFor. I suggest subclassing ObjectMapper and overriding the various writerFor methods, adding the necessary attribute at that point. You can then get Jersey to use that ObjectMapper by registering it as a JAX-RS Provider: see the various annotations in javax.ws.rs to get started on this. This answer gives an example of what to do.