gpt4 book ai didi

java - 如何将 ToXmlGenerator.Feature 添加到 Jackson2ObjectMapperBuilderCustomizer?

转载 作者:行者123 更新时间:2023-11-29 08:33:12 30 4
gpt4 key购买 nike

我有 jackson下面的bean配置。如何添加 ToXmlGenerator.Feature.WRITE_XML_DECLARATION构建器的功能?

以下不起作用:

@Bean
public Jackson2ObjectMapperBuilderCustomizer initJackson() {
return (builder) -> builder.modules(new JaxbAnnotationModule())
.defaultUseWrapper(false)
.featuresToEnable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION); //invalid!

}

结果:

Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mappingJackson2XmlHttpMessageConverter' defined in class path resource [org/springframework/boot/autoconfigure/web/JacksonHttpMessageConvertersConfiguration$MappingJackson2XmlHttpMessageConverterConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter]: Factory method 'mappingJackson2XmlHttpMessageConverter' threw exception; nested exception is org.springframework.beans.FatalBeanException: Unknown feature class: com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator$Feature

我最初的目标是在反序列化过程中添加以下行:

<?xml version="1.0" encoding="UTF-8"?> .

也许有不同的方法而不是使用 ToXmlGenerator

我还尝试了以下方法,但也没有添加 xml 声明行:

@Bean
@Primary
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
XmlMapper mapper = (XmlMapper) builder
.createXmlMapper(true)
.build();

mapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
return mapper;
}

最佳答案

它很接近,但是用于将 java bean 序列化为 xml 的 ObjectMapper 不是问题中的那个。相反,在 Jackson2ObjectMapperBuilderCustomizer 中,一个新的映射器是由 spring 自动配置创建的。这必须按如下方式覆盖:

@Bean
public MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter(
Jackson2ObjectMapperBuilder builder) {
ObjectMapper mapper = builder.createXmlMapper(true).build();
((XmlMapper) mapper).enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION);
return new MappingJackson2XmlHttpMessageConverter(mapper);
}

关于java - 如何将 ToXmlGenerator.Feature 添加到 Jackson2ObjectMapperBuilderCustomizer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46240343/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com