1

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"
             }
        ]
}
4

1 回答 1

0

进一步搜索后,我得出结论,如果不覆盖杰克逊的序列化程序,就不可能解决我的问题。

从杰克逊邮件列表中,我得到了这个答案:

您可以覆盖用于 的(反)序列化程序JsonNode,这也可用于更改多态类型 id 的处理(deserialize对于预期类型 id 的情况,有一个单独的方法,与序列化程序类似)。这可能使处理您的案件成为可能。

我想这是肯定的答案。

于 2013-10-23T22:51:10.373 回答