I'm writing a series of Java classes to represent requests and responses in a Spring MVC web service, configured to use Jackson 2.0 annotation-based JSON handling, with the jackson-databind
modules. Theses classes contain various fields, annotated where needed, to enable serialization and deserialization of JSON objects.
I have a POJO that contains a Map
field, with polymorphic values. Map values can take several types, mainly String
, other model classes, and particularly other JSON objects represented as JsonNode
.
@JsonTypeInfo(use = Id.CLASS)
private Map<String, Object> outputValues;
By using the @JsonTypeInfo
annotation, Jackson properly serializes class names in the resulting JSON, making it possible to deserialize values into the appropriate concrete type.
For instance, for a value of type ArrayNode
(a subtype of JsonNode
), Jackson will explicitly add the type name "com.fasterxml.jackson.databind.node.ArrayNode"
, in the resulting JSON.
outputValues: {
result: [
"com.fasterxml.jackson.databind.node.ArrayNode",
[
{
Content-Type: "application/json",
url: "http://server.url"
},
{
Content-Type: "application/json",
url: "http://server.url.2"
}
]
]
}
What I wish to achieve is a special case where, when a JsonNode
or one of its subtypes are encountered as a map value, the JSON object is serialised without explicitly adding the type name into. In this example, at deserialization time, Jackson would produce ArrayNode
when it found an unknown array structure. It would still continue to produce other polymorphic types when it encountered.
The above example would look like this:
outputValues: {
result:
[
{
Content-Type: "application/json",
url: "http://server.url"
},
{
Content-Type: "application/json",
url: "http://server.url.2"
}
]
}