2017-05-29 117 views
0

我需要使用两个杰克逊2对象映射器。 这两个映射器都使用同一组类。 在第一个我需要使用标准序列化。 在第二我想使用ARRAY形状类型的所有类(见https://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonFormat.Shape.html#ARRAY)。杰克逊ObjectMapper设置JsonFormat.Shape.ARRAY没有注释

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

如何做到这一点?

UPD:

我找到了一种方法来覆盖配置为类:

mapper.configOverride(MyClass.class) 
    .setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.ARRAY)); 

这样我就可以使用反射API的所有我的课改变。

令人尴尬的是,我重写了全局设置,但我无法直接设置它。

回答

2

由于@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(); 
    } 
} 

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

ObjectMapper mapper = new ObjectMapper(); 
SimpleModule module = new SimpleModule(); 
module.addSerializer(String.class, new CustomDeserializer()); 
mapper.registerModule(module);