5

我有一个包含带有 @XmlElement 标签的元素的合同类。例如

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

使用 JAXBContext 我能够生成带有适当标签的 xml。

但是,当我使用杰克逊提供的库时,JSON 标记仍然以“balanceMoney”而不是“balancemoney”的形式出现

我如何告诉杰克逊考虑 @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));

}
4

2 回答 2

9
  • 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));
    }
    
于 2015-08-12T23:58:46.553 回答
2

根据Using JAXB annotations with Jackson : Enabling JAXB annotation support,您需要设置mapper.getDeserializationConfig().setAnnotationIntrospector(new JaxbAnnotationIntrospector());为使 Jackson 能够使用 JAXB annotation。

于 2013-10-26T06:56:55.140 回答