将Jackson jaxrs xml提供程序从2.4.1版升级到2.5.0时,我遇到了一些问题。我在基于Jersey(v1.19)的REST API项目中使用xml提供程序。
新版本:com.fasterxml.jackson.jaxrs:jackson-jaxrs-xml-provider:2.5.0
问题: 在序列化期间不会调用为自定义默认Jackson序列化而编写的自定义序列化程序。这些自定义序列化程序正在使用v2.4.1,因此在升级之后,API没有返回所需的输出结构。
请在下面找到我的ContextResolver和自定义序列化器的实现:
XmlMapperContextResolver.java
@Provider
@Produces({MediaType.APPLICATION_XML })
public class XmlMapperContextResolver implements ContextResolver<XmlMapper> {
private final XmlMapper animalXmlMapper = new XmlMapper();
private final XmlMapper defaultXmlMapper = new XmlMapper();
@Override
public XmlMapper getContext(Class<?> type) {
if (Animal.class.isAssignableFrom(type)) {
return animalXmlMapper;
}
return defaultXmlMapper;
}
public XmlMapperContextResolver() {
JacksonXmlModule module = new JacksonXmlModule();
module.setDefaultUseWrapper(false);
// Adding Serializers
module.addSerializer(CharacterMap.class, new CharacterMapSerializer());
animalXmlMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
animalXmlMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
animalXmlMapper.registerModule(module);
defaultXmlMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
defaultXmlMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
}
}
CharacterMapSerializer.java
public class CharacterMapSerializer extends
JsonSerializer<Map<String, Character>> {
@Override
public void serialize(Map<String, Character> value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
provider.defaultSerializeField("Character", value.values(), jgen);
}
}
CharacterMap.java
public class CharacterMap extends HashMap<String, Character> {
}
在执行期间调用XmlMapperContextResolver
并成功返回animalXmlMapper的实例。但是在序列化响应时,CharacterMapSerializer
不会被调用,而是Jackson应用其默认的序列化技术来构建XML响应。