static final ObjectMapper mapper = ...; // only create once, acts as factor
// later on
byte[] json = mapper.writer(SerializationFeature.INDENT_OUTPUT)
.without(SerializationFeature. WRAP_EXCEPTIONS)
.writeValueAsBytes(value);
MyType result = mapper.readerFor(MyType.class)
.with(DeserializationFeature.UNWRAP_ROOT_VALUE)
// and more 'with' or 'without' calls
readValue(json);
2条答案
按热度按时间nafvub8i1#
实际上,如果你想在每次调用的基础上修改
SerializationFeature
或DeserializationFeature
,你不想使用ObjectMapper
中的方法,而是像这样构造ObjectReader
和/或ObjectWriter
:请注意,
ObjectMapper
的构造成本很高,而且示例绝对需要重用,而ObjectReader
和ObjectWriter
的构造成本很低,并且是在每次读/写的基础上完成的。因此,尽管它们可以重用(示例是完全线程安全的,不可变的),但并不一定需要太多。yshpjwxd2#
最终,我通过为内部类型定义自己的反序列化器,并在内部定义自己的新静态ObjectMapper来保存所需的配置,解决了这个问题。