Jackson ObjectMapper 设置 JsonFormat.Shape.ARRAY 不带注释

Анд*_*аев 5 java spring json jackson objectmapper

我需要使用两个 jackson 2 对象映射器。两个映射器都使用同一组类。首先,我需要使用标准序列化。在第二个中,我想对所有类使用 ARRAY 形状类型(请参阅https://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonFormat.Shape.html#ARRAY)。

但我想为我的第二个 ObjectMapper 全局设置此功能。类似mapper.setShape(...)

怎么做?

更新:

我找到了一种覆盖该类配置的方法:

mapper.configOverride(MyClass.class)
   .setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.ARRAY));
Run Code Online (Sandbox Code Playgroud)

所以我可以使用 Reflection API 更改我的所有类。

尴尬的是我覆盖了全局设置,但又不能直接设置。

Dar*_*hta 1

由于@JsonFormat注释适用于字段,因此您无法将其设置为Shape.Array全局级别。这意味着所有字段都将被序列化和反序列化为数组值(想象一下,如果一个字段已经是一个列表,在这种情况下,它将被包装到另一个列表中,这是我们可能不想要的)。

但是,您可以编写自己的serializer类型(将值转换为数组)并在 中配置它ObjectMapper,例如:

class CustomDeserializer extends JsonSerializer<String>{

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers)
            throws IOException, JsonProcessingException {
        gen.writeStartArray();
        gen.writeString(value);
        gen.writeEndArray();
    }
}
Run Code Online (Sandbox Code Playgroud)

并将其配置为ObjectMaper实例,例如:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(String.class, new CustomDeserializer());
mapper.registerModule(module);
Run Code Online (Sandbox Code Playgroud)