杰克逊ObjectMapper设置JsonFormat.Shape.ARRAY不带注释 [英] Jackson ObjectMapper set JsonFormat.Shape.ARRAY without annotation
问题描述
我需要使用两个杰克逊2对象映射器. 两个映射器都使用相同的类集. 首先,我需要使用标准序列化. 在第二个中,我想对所有类使用ARRAY形状类型(请参见
I need to use two jackson 2 object mappers. Both mappers work with the same set of classes. In the first I need to use standard serialization. In the second i want to use ARRAY shape type for all classes (see https://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonFormat.Shape.html#ARRAY).
但是我想为第二个ObjectMapper全局设置此功能.就像mapper.setShape(...)
But i want to global set this feature for my second ObjectMapper. Something like mapper.setShape(...)
该怎么做?
UPD:
我找到了一种覆盖该类配置的方法:
I found a way to override the config for the class:
mapper.configOverride(MyClass.class)
.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.ARRAY));
因此,我可以使用Reflection API更改所有类.
So I can change for all my classes using Reflection API.
令人尴尬的是我覆盖了全局设置,但是我不能直接设置它.
It is embarrassing that I override the global setting, but I can not directly set it.
推荐答案
由于@JsonFormat
注释在字段上有效,因此无法在全局级别将其设置为Shape.Array
.这意味着所有字段都将被序列化并反序列化为数组值(想象一下,如果一个字段已经是一个列表,在这种情况下,它将被包装到另一个我们可能不想要的列表中).
As @JsonFormat
annotation works on field, you can't set it to Shape.Array
at global level. This would mean all the fields would be serialized and deserialised into array values (imagine if a field is already a list, in this case, it will be wrapped into another list which is something we might not want).
但是,您可以为类型(将值转换为数组)编写自己的serializer
并在ObjectMapper
中对其进行配置,例如:
You can however, write your own serializer
for a type (that converts a value into an array) and configure it in ObjectMapper
, e.g.:
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
实例,例如:
And configure it to ObjectMaper
instance, e.g.:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(String.class, new CustomDeserializer());
mapper.registerModule(module);
这篇关于杰克逊ObjectMapper设置JsonFormat.Shape.ARRAY不带注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!