Jackson unable to consider @XmlElement while serializing to JSON

前端 未结 2 1104
闹比i
闹比i 2020-12-19 20:47

I have a contract class that contains elements with @XmlElement tags. For ex

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

相关标签:
2条回答
  • 2020-12-19 21:23

    According to Using JAXB annotations with Jackson: Enabling JAXB annotation support, you need to set mapper.getDeserializationConfig().setAnnotationIntrospector(new JaxbAnnotationIntrospector()); to enable Jackson to use JAXB annotation.

    0 讨论(0)
  • 2020-12-19 21:25
    • Maven dependency - pom.xml:

      <dependency>
          <groupId>com.fasterxml.jackson.module</groupId>
          <artifactId>jackson-module-jaxb-annotations</artifactId>
          <version>2.6.1</version>
      </dependency>
      
    • Custom ObjectMapper configuration (uncomment all annotations to register this mapper as default in 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;
          }
      }
      
    • Code to display as JSON:

      public void displayJSON(Object reqResp) throws JsonProcessingException{
          ObjectMapper mapper = JacksonConfig.createCustomObjectMapper();
          LOG.info(mapper.writeValueAsString(reqResp));
      }
      
    0 讨论(0)
提交回复
热议问题