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

时间:2013-10-26 00:19:31

标签: xml jaxb jackson

我有一个包含@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));

}

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

  • Maven依赖--pom.xml:

    <dependency>
        <groupId>com.fasterxml.jackson.module</groupId>
        <artifactId>jackson-module-jaxb-annotations</artifactId>
        <version>2.6.1</version>
    </dependency>
    
  • 自定义ObjectMapper配置(取消注释所有注释以在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));
    }