Jackson在序列化为JSON时无法考虑@XmlElement

nlejzf6q  于 2023-11-19  发布在  其他
关注(0)|答案(3)|浏览(116)

我有一个合约类,它包含带有@XmlElement标记的元素。

@XmlElement(name = "balancemoney")
 protected Amount balanceMoney;

字符串
使用JAXBContext,我能够生成带有适当标记的xml。
然而,当我使用Jackson提供的库时,JSON标记仍然是“balanceMoney”,而不是“balancemoney”。
如何告诉Jackson考虑使用@XmlElement标记。
下面是实现这一点的代码。

//Function to display request object.
public void displayXML(Object reqResp){
    try{
        JAXBContext jaxbContext = JAXBContext.newInstance(reqResp.getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        ByteArrayOutputStream bStream=new ByteArrayOutputStream();

        //jaxbMarshaller.marshal(reqResp, System.out);
        jaxbMarshaller.marshal(reqResp,bStream );

        logger.info(bStream.toString());    

        }catch(JAXBException e){
            logger.info(e.getMessage());
        }
        logger.info("*** Payload is: " + reqResp.toString());
}

//Function to display as JSON
public void displayJSON(Object reqResp) throws JsonGenerationException, JsonMappingException, IOException{
    ObjectMapper mapper = new ObjectMapper();
    logger.info(mapper.defaultPrettyPrintingWriter().writeValueAsString(reqResp));

}

lhcgjxsq

lhcgjxsq1#

  • Maven依赖项- pom.xml:
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-jaxb-annotations</artifactId>
    <version>2.6.1</version>
</dependency>

字符串

  • 自定义ObjectMapper配置(取消注解所有注解以将此Map器注册为Spring中的默认值):
//@Configuration
public class JacksonConfig {

    //@Primary
    //@Bean
    public static ObjectMapper createCustomObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        AnnotationIntrospector aiJaxb = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
        AnnotationIntrospector aiJackson = new JacksonAnnotationIntrospector();
        // first Jaxb, second Jackson annotations
        mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(aiJaxb, aiJackson));
        return mapper;
    }
}

  • 要显示为JSON的代码:
public void displayJSON(Object reqResp) throws JsonProcessingException{
    ObjectMapper mapper = JacksonConfig.createCustomObjectMapper();
    LOG.info(mapper.writeValueAsString(reqResp));
}

kyvafyod

kyvafyod2#

根据Using JAXB annotations with Jackson启用JAXB注解支持,需要设置mapper.getDeserializationConfig().setAnnotationIntrospector(new JaxbAnnotationIntrospector());,使Jackson使用JAXB注解。

dzhpxtsq

dzhpxtsq3#

如果我们在Jaxbclasses中从Javax迁移到Jakarta,那么下面应该可以工作

XmlMapper xmlMapper = new XmlMapper();
      xmlMapper.registerModule(new JakartaXmlBindAnnotationModule());

字符串

相关问题