簡體   English   中英

Jackson在序列化為JSON時無法考慮@XmlElement

[英]Jackson unable to consider @XmlElement while serializing to JSON

我有一個合同類,其中包含帶有@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));

}
  • 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)); } 

根據Jackson使用JAXB注釋啟用JAXB注釋支持 ,您需要設置mapper.getDeserializationConfig().setAnnotationIntrospector(new JaxbAnnotationIntrospector()); 使Jackson能夠使用JAXB注釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM